Basic Java Programs

Naveen AnamaneniUpdated · 5 min read

You learn to drive by driving, not by reading about the clutch. These are the programs almost every Java beginner writes, and almost every fresher interview asks one of. Each uses only what the Java Language Basics, Input and Output, and Control Statements chapters taught: variables, operators, conditions and loops. Try each one yourself before reading the solution, then compare.

Pattern 1: Right Triangle and Pyramid

Patterns.java▶ Try it
public class Patterns {
    public static void main(String[] args) {
        int n = 4;
        for (int i = 1; i <= n; i++) {
            System.out.println("*".repeat(i));
        }
        System.out.println();
 
        for (int i = 1; i <= n; i++) {
            for (int s = 1; s <= n - i; s++) {
                System.out.print(" ");
            }
            for (int j = 1; j <= 2 * i - 1; j++) {
                System.out.print("*");
            }
            System.out.println();
        }
    }
}
Output
*
**
***
****
 
   *
  ***
 *****
*******

How it works

  1. The triangle uses "*".repeat(i), which makes a string of i stars (Java 11+).
  2. The pyramid's row i needs n - i spaces, then 2 * i - 1 stars: 1, 3, 5, 7.
  3. Work out the rule for one row first; the loops just apply it to every row.

Pattern 2: Number Triangle

Numbers.java▶ Try it
public class Numbers {
    public static void main(String[] args) {
        for (int i = 1; i <= 4; i++) {
            for (int j = 1; j <= i; j++) {
                System.out.print(j);
            }
            System.out.println();
        }
    }
}
Output
1
12
123
1234

Prime Check

A prime number has exactly two divisors: 1 and itself. It's enough to try divisors up to the square root, because any larger divisor has a smaller partner.

Prime.java▶ Try it
public class Prime {
    public static void main(String[] args) {
        int n = 97;
        boolean prime = n > 1;
        for (int d = 2; d * d <= n; d++) {
            if (n % d == 0) {
                prime = false;
                break;
            }
        }
        System.out.println(n + (prime ? " is prime" : " is not prime"));
    }
}
Output
97 is prime

d * d <= n stops at the square root: for 97, only 2 to 9 are tried. The first divisor found ends the loop with break.

Factorial and Fibonacci

Series.java▶ Try it
public class Series {
    public static void main(String[] args) {
        long factorial = 1;
        for (int i = 2; i <= 15; i++) {
            factorial *= i;
        }
        System.out.println("15! = " + factorial);
 
        int a = 0, b = 1;
        System.out.print("Fibonacci: " + a);
        for (int i = 1; i < 10; i++) {
            System.out.print(", " + b);
            int next = a + b;
            a = b;
            b = next;
        }
        System.out.println();
    }
}
Output
15! = 1307674368000
Fibonacci: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34

The factorial uses long, because 13! already overflows an int. Each Fibonacci number is the sum of the previous two, so the loop keeps just two variables and moves them along.

Palindrome and Armstrong Numbers

A palindrome reads the same backwards, like 12321. An Armstrong number equals the sum of its digits, each raised to the power of the number of digits: 153 = 1³ + 5³ + 3³.

Digits.java▶ Try it
public class Digits {
    public static void main(String[] args) {
        int n = 12321, reversed = 0, temp = n;
        while (temp > 0) {
            reversed = reversed * 10 + temp % 10;
            temp /= 10;
        }
        String isPal = n == reversed ? " is" : " is not";
        System.out.println(n + isPal + " a palindrome");
 
        int m = 153, sum = 0;
        int digits = String.valueOf(m).length();
        temp = m;
        while (temp > 0) {
            int d = temp % 10;
            sum += (int) Math.pow(d, digits);
            temp /= 10;
        }
        String isArm = m == sum ? " is" : " is not";
        System.out.println(m + isArm + " an Armstrong number");
    }
}
Output
12321 is a palindrome
153 is an Armstrong number

Both use the same digit trick as the while lesson: % 10 takes the last digit and / 10 removes it.

Interview Corner

How do you check whether a number is prime?

Return false for numbers below 2. Otherwise, try every divisor d from 2 while d * d <= n; if any divides n exactly, it isn't prime. Checking up to the square root is enough, because every larger divisor pairs with a smaller one.

How do you reverse a number without converting it to a String?

Repeatedly take the last digit with n % 10, append it with reversed = reversed * 10 + digit, and drop it with n /= 10 until n is 0.

Practice

  1. Easy: Print an inverted triangle of stars: 4, 3, 2, 1 stars.
  2. Harder: Print all prime numbers between 1 and 50 on one line, reusing the prime check inside a loop.
  3. Harder: Print all three-digit Armstrong numbers (there are four).

Quick check: Basic programs

4 questions
1Why does the prime check stop at d * d <= n?
2Why is factorial a long?
3In the pyramid, how many stars are on row i?
4What does temp % 10 give inside the digit loops?

Key Takeaways

Was this tutorial helpful?

Lesson 67 of 482