20 Basic Java Programs for Practice
You can't learn to swim by reading about swimming. At some point you have to get into the pool, splash about, swallow a little water and try again. Programming is the same: the lessons explain the ideas, but the ideas only stick once you write programs yourself. Here are 20 classic programs that use everything from the first level of the course: variables, operators, input with Scanner, decisions, loops, methods and arrays. Each one gives a sample input and the output to expect. Write the program yourself first, run it with the sample input, and compare. Only then open the hint, and after that the solution.
How to Use This Page
- Write it yourself. Create a class, read the input with
Scanner, and print the result in exactly the format shown. - Run it with the sample input and compare your output character by character.
- Test an edge case too: 0, a negative number, or the smallest valid input. Each program suggests one.
- Stuck for more than 15 minutes? Open the hint. Still stuck? Open the solution, read it, close it, and write it again from memory.
Input, Operators and Decisions
1. Sum and Average of Three Numbers
Input: 10 20 25 · Expected output: Sum = 55, Average = 18.33
You practice: Scanner, printf, and the difference between integer and floating-point division.
Show hint
Divide by 3.0, not 3, or the average loses its decimals.
Show solution
import java.util.Scanner;
public class SumAverage {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int a = in.nextInt();
int b = in.nextInt();
int c = in.nextInt();
int sum = a + b + c;
System.out.printf("Sum = %d, Average = %.2f%n", sum, sum / 3.0);
}
}Sum = 55, Average = 18.332. Even or Odd
Input: 7 · Expected output: 7 is odd · Edge case: -3 should print -3 is odd
You practice: the % operator and the conditional operator.
Show hint
-3 % 2 is -1, not 1. So test n % 2 == 0 for even, rather than n % 2 == 1 for odd.
Show solution
import java.util.Scanner;
public class EvenOdd {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n = in.nextInt();
System.out.println(n + (n % 2 == 0 ? " is even" : " is odd"));
}
}7 is odd3. Largest of Three Numbers
Input: 4 9 2 · Expected output: Largest = 9
You practice: the else-if ladder, and then Math.max.
Show hint
Solve it with if-else first. Then try it in one line with Math.max(a, Math.max(b, c)).
Show solution
import java.util.Scanner;
public class LargestOfThree {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int a = in.nextInt();
int b = in.nextInt();
int c = in.nextInt();
int largest;
if (a >= b && a >= c) {
largest = a;
} else if (b >= c) {
largest = b;
} else {
largest = c;
}
System.out.println("Largest = " + largest);
}
}Largest = 94. Leap Year
Input: 2024 · Expected output: 2024 is a leap year · Also try: 1900 (not a leap year) and 2000 (a leap year)
You practice: logical operators and their precedence.
Show hint
A year is a leap year if it is divisible by 4, except century years, unless they are divisible by 400.
Show solution
import java.util.Scanner;
public class LeapYear {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int y = in.nextInt();
boolean leap = (y % 4 == 0 && y % 100 != 0) || y % 400 == 0;
String answer = leap ? " is a leap year" : " is not a leap year";
System.out.println(y + answer);
}
}2024 is a leap year5. Simple Calculator
Input: 8 / 2 · Expected output: 4.0 · Edge case: 5 / 0 should print NaN
You practice: the switch expression with yield.
Show hint
Read the operator as a word with in.next() and take its first character with charAt(0).
Show solution
import java.util.Scanner;
public class Calculator {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
double a = in.nextDouble();
char op = in.next().charAt(0);
double b = in.nextDouble();
double result = switch (op) {
case '+' -> a + b;
case '-' -> a - b;
case '*' -> a * b;
case '/' -> b == 0 ? Double.NaN : a / b;
default -> {
System.out.println("Unknown operator: " + op);
yield Double.NaN;
}
};
System.out.println(result);
}
}4.0Loops
6. Multiplication Table
Input: 7 · Expected output: ten lines from 7 x 1 = 7 to 7 x 10 = 70, with the numbers lined up
You practice: the for loop and widths in format specifiers.
Show hint
%2d prints a number in 2 characters, padding with a space on the left. Use it for i, and %3d for the product.
Show solution
import java.util.Scanner;
public class MultiplicationTable {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n = in.nextInt();
for (int i = 1; i <= 10; i++) {
System.out.printf("%d x %2d = %3d%n", n, i, n * i);
}
}
}7 x 1 = 7
7 x 2 = 14
7 x 3 = 21
7 x 4 = 28
7 x 5 = 35
7 x 6 = 42
7 x 7 = 49
7 x 8 = 56
7 x 9 = 63
7 x 10 = 707. Factorial
Input: 5 · Expected output: 120 · Edge case: 0 should print 1
You practice: loops, the long type, and overflow.
Show hint
Start with long fact = 1 and multiply by 2, 3, ... up to n. A long holds factorials only up to 20!. Try 21 and explain the strange result.
Show solution
import java.util.Scanner;
public class Factorial {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n = in.nextInt();
long fact = 1;
for (int i = 2; i <= n; i++) {
fact *= i;
}
System.out.println(fact);
}
}1208. Fibonacci Series
Input: 8 · Expected output: 0 1 1 2 3 5 8 13
You practice: a loop with two running variables.
Show hint
Keep the current number a and the next one b. Each step, print a, then move both forward: the new a is b, and the new b is a + b.
Show solution
import java.util.Scanner;
public class Fibonacci {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n = in.nextInt();
long a = 0;
long b = 1;
for (int i = 0; i < n; i++) {
if (i > 0) {
System.out.print(" ");
}
System.out.print(a);
long next = a + b;
a = b;
b = next;
}
System.out.println();
}
}0 1 1 2 3 5 8 13Numbers and Methods
9. Prime Check
Input: 29 · Expected output: 29 is prime · Edge case: 1 should print 1 is not prime
You practice: a method that returns boolean, and leaving a loop early.
Show hint
You only need to test divisors up to the square root of n. Write the loop condition as i * i <= n so you don't need Math.sqrt.
Show solution
import java.util.Scanner;
public class PrimeCheck {
static boolean isPrime(int n) {
if (n < 2) {
return false;
}
for (int i = 2; (long) i * i <= n; i++) {
if (n % i == 0) {
return false;
}
}
return true;
}
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n = in.nextInt();
System.out.println(n + (isPrime(n) ? " is prime" : " is not prime"));
}
}29 is prime10. All Primes Up to N
Input: 20 · Expected output: 2 3 5 7 11 13 17 19
You practice: reusing a method you already wrote.
Show hint
Reuse isPrime from the previous program and call it for every number from 2 to n. For a challenge, try the Sieve of Eratosthenes with a boolean[].
Show solution
import java.util.Scanner;
public class PrimesUpToN {
static boolean isPrime(int n) {
if (n < 2) {
return false;
}
for (int i = 2; (long) i * i <= n; i++) {
if (n % i == 0) {
return false;
}
}
return true;
}
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n = in.nextInt();
StringBuilder primes = new StringBuilder();
for (int i = 2; i <= n; i++) {
if (isPrime(i)) {
if (!primes.isEmpty()) {
primes.append(' ');
}
primes.append(i);
}
}
System.out.println(primes);
}
}2 3 5 7 11 13 17 1911. Reverse a Number
Input: 1234 · Expected output: 4321
You practice: taking digits off with % 10 and / 10.
Show hint
n % 10 is the last digit and n / 10 drops it. Build the answer with rev = rev * 10 + digit.
Show solution
import java.util.Scanner;
public class ReverseNumber {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n = in.nextInt();
int rev = 0;
while (n != 0) {
rev = rev * 10 + n % 10;
n /= 10;
}
System.out.println(rev);
}
}432112. Palindrome Number
Input: 121 · Expected output: 121 is a palindrome · Also try: 123, which is not a palindrome
You practice: combining the previous program with a comparison.
Show hint
Keep a copy of the original number, because the loop changes n until it reaches 0.
Show solution
import java.util.Scanner;
public class PalindromeNumber {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n = in.nextInt();
int original = n;
int rev = 0;
while (n > 0) {
rev = rev * 10 + n % 10;
n /= 10;
}
if (original == rev) {
System.out.println(original + " is a palindrome");
} else {
System.out.println(original + " is not a palindrome");
}
}
}121 is a palindrome13. Armstrong Number
Input: 153 · Expected output: 153 is an Armstrong number (1³ + 5³ + 3³ = 153) · Also try: 9474 (yes) and 123 (no)
You practice: counting digits and Math.pow.
Show hint
First count the digits, k. Then add each digit raised to the power k, and compare the total with the number.
Show solution
import java.util.Scanner;
public class ArmstrongNumber {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n = in.nextInt();
int k = String.valueOf(n).length();
int sum = 0;
for (int t = n; t > 0; t /= 10) {
sum += (int) Math.pow(t % 10, k);
}
if (sum == n) {
System.out.println(n + " is an Armstrong number");
} else {
System.out.println(n + " is not an Armstrong number");
}
}
}153 is an Armstrong number14. Sum of Digits
Input: 9875 · Expected output: 29 · Edge case: -9875 should also print 29
You practice: a loop over the digits of a number.
Show hint
Use Math.abs(n) first, so a negative number works too.
Show solution
import java.util.Scanner;
public class SumOfDigits {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n = in.nextInt();
int sum = 0;
for (int t = Math.abs(n); t > 0; t /= 10) {
sum += t % 10;
}
System.out.println(sum);
}
}2915. GCD and LCM
Input: 12 18 · Expected output: GCD = 6, LCM = 36
You practice: Euclid's algorithm and recursion.
Show hint
gcd(a, b) is a when b is 0, and otherwise gcd(b, a % b). Compute the LCM as a / gcd * b, dividing first so the numbers stay small.
Show solution
import java.util.Scanner;
public class GcdLcm {
static int gcd(int a, int b) {
return b == 0 ? a : gcd(b, a % b);
}
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int a = in.nextInt();
int b = in.nextInt();
int g = gcd(a, b);
long lcm = (long) a / g * b;
System.out.println("GCD = " + g + ", LCM = " + lcm);
}
}GCD = 6, LCM = 36Patterns
16. Right-Angled Star Triangle
Input: 4 · Expected output:
*
**
***
****You practice: nested loops.
Show hint
The outer loop picks the row, i. The inner loop prints i stars, and then the row ends with a new line.
Show solution
import java.util.Scanner;
public class StarTriangle {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n = in.nextInt();
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= i; j++) {
System.out.print("*");
}
System.out.println();
}
}
}*
**
***
****17. Pyramid
Input: 4 · Expected output:
*
***
*****
*******You practice: nested loops with two counts in each row.
Show hint
Row i has n - i spaces and then 2 * i - 1 stars. Solve it with loops, then try " ".repeat(n - i) + "*".repeat(2 * i - 1).
Show solution
import java.util.Scanner;
public class Pyramid {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n = in.nextInt();
for (int i = 1; i <= n; i++) {
for (int s = 0; s < n - i; s++) {
System.out.print(" ");
}
for (int k = 0; k < 2 * i - 1; k++) {
System.out.print("*");
}
System.out.println();
}
}
} *
***
*****
*******Arrays
18. Largest and Smallest in an Array
Input: 5, then the five numbers 5 1 9 3 7 · Expected output: Max = 9, Min = 1
You practice: reading values into an array and going through it once.
Show hint
Start both max and min from arr[0], not from 0, so an array of only negative numbers still works.
Show solution
import java.util.Scanner;
public class MaxMin {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int[] arr = new int[in.nextInt()];
for (int i = 0; i < arr.length; i++) {
arr[i] = in.nextInt();
}
int max = arr[0];
int min = arr[0];
for (int x : arr) {
if (x > max) {
max = x;
}
if (x < min) {
min = x;
}
}
System.out.println("Max = " + max + ", Min = " + min);
}
}Max = 9, Min = 119. Second Largest Element
Input: 5, then 5 1 9 3 9 · Expected output: 5 (a second copy of the largest doesn't count)
You practice: tracking two values in one pass.
Show hint
Sorting works but does more work than needed. Instead keep first and second while you go through the array once, and skip values equal to first.
Show solution
import java.util.Scanner;
public class SecondLargest {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int[] arr = new int[in.nextInt()];
for (int i = 0; i < arr.length; i++) {
arr[i] = in.nextInt();
}
int first = Integer.MIN_VALUE;
int second = Integer.MIN_VALUE;
for (int x : arr) {
if (x > first) {
second = first;
first = x;
} else if (x > second && x != first) {
second = x;
}
}
if (second == Integer.MIN_VALUE) {
System.out.println("No second largest");
} else {
System.out.println(second);
}
}
}520. Reverse an Array in Place
Input: 5, then 1 2 3 4 5 · Expected output: [5, 4, 3, 2, 1]
You practice: swapping with two indexes, and Arrays.toString.
Show hint
Don't create a second array. Swap the first and last elements, then move both indexes one step inwards, until they meet.
Show solution
import java.util.Arrays;
import java.util.Scanner;
public class ReverseArray {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int[] arr = new int[in.nextInt()];
for (int i = 0; i < arr.length; i++) {
arr[i] = in.nextInt();
}
for (int i = 0, j = arr.length - 1; i < j; i++, j--) {
int tmp = arr[i];
arr[i] = arr[j];
arr[j] = tmp;
}
System.out.println(Arrays.toString(arr));
}
}[5, 4, 3, 2, 1]What Next
Solved all 20 without opening the solutions? Then you are ready for the Level 1 test. Found some hard? That's normal. Go back to the lesson behind the program ("Java Operators", "Java for Loop", "Nested Loops" or "Java Arrays"), and try the program again in a few days.
Was this tutorial helpful?