All Java Exercises
Print your name and age with variables
Description: Create a String variable for your name and an int variable for your age. Print the sentence My name is Riya and I am 21 years old. (use your own values).
Hint:
- Join text and variables with
+. - Or use
String.format()with%sand%d.
Solution
public class Main {
public static void main(String[] args) {
String name = "Riya";
int age = 21;
System.out.println("My name is " + name + " and I am " + age + " years old.");
System.out.println(String.format("My name is %s and I am %d years old.", name, age));
}
}
My name is Riya and I am 21 years old.
My name is Riya and I am 21 years old.
How it works
+joins aStringwith other values, and Java changes the number to text.%sand%dinString.format()are placeholders for text and whole numbers.
Read Java Variables.
Swap two numbers with and without a third variable
Description: Swap the values of a = 10 and b = 25. First use a third variable. Then do it without a third variable.
Hint:
- With three variables:
temp = a; a = b; b = temp; - Without: use addition and subtraction.
Solution
public class Main {
public static void main(String[] args) {
int a = 10, b = 25;
int temp = a; // way 1: a third variable
a = b;
b = temp;
System.out.println("a = " + a + ", b = " + b);
a = a + b; // way 2: no third variable
b = a - b;
a = a - b;
System.out.println("a = " + a + ", b = " + b);
}
}
a = 25, b = 10
a = 10, b = 25
How it works
- The first way keeps one value safe in
tempbefore it is replaced. - In the second way,
abecomes the sum, and then each variable gets the other value by subtraction. (Be careful: with very big numbers the sum can overflow.)
Read Java Operators.
Convert Celsius to Fahrenheit
Description: Write a method toFahrenheit(double celsius) using F = C x 9 / 5 + 32. Print the result for 0, 37 and 100 degrees.
Hint:
- Use
doubleto keep the decimals. - Write
9.0 / 5, not9 / 5(that is integer division).
Solution
public class Main {
static double toFahrenheit(double celsius) {
return celsius * 9.0 / 5 + 32;
}
public static void main(String[] args) {
for (double c : new double[]{0, 37, 100}) {
System.out.printf("%.1f C = %.1f F%n", c, toFahrenheit(c));
}
}
}
0.0 C = 32.0 F
37.0 C = 98.6 F
100.0 C = 212.0 F
How it works
9.0 / 5is a decimal division (1.8). With9 / 5the answer would be1.printfwith%.1fprints one digit after the decimal point.
Read Java Methods.
Find the largest of three numbers
Description: Write a method which gets three int numbers and returns the largest one. Test it with (12, 45, 30) and (7, 7, 3).
Hint:
- Use
ifwith&&, or callMath.max()two times.
Solution
public class Main {
static int largest(int a, int b, int c) {
if (a >= b && a >= c) return a;
if (b >= c) return b;
return c;
}
public static void main(String[] args) {
System.out.println(largest(12, 45, 30));
System.out.println(largest(7, 7, 3));
System.out.println(Math.max(12, Math.max(45, 30))); // shorter way
}
}
45
7
45
How it works
- The first
ifchecks ifais at least as big as both others. - If not, the winner is
borc, so one more comparison is enough.
Read Java if else.
Check if a year is a leap year
Description: Write a method isLeap(int year). A year is a leap year if it is divisible by 4, but not by 100, unless it is divisible by 400. Test 1900, 2000, 2024 and 2026.
Hint:
- Use the remainder operator
%.
Solution
public class Main {
static boolean isLeap(int year) {
return (year % 4 == 0 && year % 100 != 0) || year % 400 == 0;
}
public static void main(String[] args) {
for (int y : new int[]{1900, 2000, 2024, 2026}) {
System.out.println(y + " -> " + isLeap(y));
}
System.out.println(java.time.Year.isLeap(2024)); // the library method
}
}
1900 -> false
2000 -> true
2024 -> true
2026 -> false
true
How it works
- 1900 is divisible by 100 but not by 400, so it is not a leap year. 2000 is divisible by 400, so it is.
- Java has this check ready:
Year.isLeap().
Read Java Operators.
FizzBuzz in Java
Description: Print the numbers from 1 to 15. For multiples of 3 print Fizz, for multiples of 5 print Buzz, and for multiples of both print FizzBuzz.
Hint:
- Check the multiples of 15 (both) first.
Solution
public class Main {
public static void main(String[] args) {
for (int i = 1; i <= 15; i++) {
if (i % 15 == 0) {
System.out.println("FizzBuzz");
} else if (i % 3 == 0) {
System.out.println("Fizz");
} else if (i % 5 == 0) {
System.out.println("Buzz");
} else {
System.out.println(i);
}
}
}
}
1
2
Fizz
4
Buzz
Fizz
7
8
Fizz
Buzz
11
Fizz
13
14
FizzBuzz
How it works
- If you check 3 first, then 15 would print only
Fizz. So the most special case must come first.
Read Java for Loop.
Sum of the digits of a number
Description: Write a method which returns the sum of the digits of a positive number. For 9475 the answer is 25.
Hint:
n % 10is the last digit,n / 10removes it.
Solution
public class Main {
static int digitSum(int n) {
int sum = 0;
while (n > 0) {
sum += n % 10;
n /= 10;
}
return sum;
}
public static void main(String[] args) {
System.out.println(digitSum(9475));
System.out.println(digitSum(100));
System.out.println(digitSum(0));
}
}
25
1
0
How it works
- The loop takes the last digit, adds it, and removes it, until the number becomes 0.
Read Java while Loop.
Print a multiplication table
Description: Print the table of 7 from 1 to 10 in the format 7 x 3 = 21.
Hint:
- A for loop from 1 to 10 and
printf.
Solution
public class Main {
public static void main(String[] args) {
int n = 7;
for (int i = 1; i <= 10; i++) {
System.out.printf("%d x %2d = %2d%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 = 70
How it works
%2duses at least 2 places, so the numbers line up in columns.
Read Java for Loop.
Check if a number is prime
Description: Write isPrime(int n). A prime number is bigger than 1 and has no divisor except 1 and itself. Print all the primes up to 30.
Hint:
- You only need to test divisors up to the square root of
n.
Solution
public class Main {
static boolean isPrime(int n) {
if (n < 2) return false;
for (int i = 2; i * i <= n; i++) {
if (n % i == 0) return false;
}
return true;
}
public static void main(String[] args) {
for (int n = 1; n <= 30; n++) {
if (isPrime(n)) System.out.print(n + " ");
}
System.out.println();
}
}
2 3 5 7 11 13 17 19 23 29
How it works
- If
nhas a divisor bigger than its square root, it must also have a smaller one, so testing up toi * i <= nis enough. - The method returns
falseas soon as it finds a divisor.
Read Java Methods.
Reverse a string
Description: Reverse the text "Java" to "avaJ". Do it with a loop and with StringBuilder.
Hint:
- Go from the last index to 0 and join the characters.
StringBuilderhas areverse()method.
Solution
public class Main {
static String reverseLoop(String s) {
String result = "";
for (int i = s.length() - 1; i >= 0; i--) {
result += s.charAt(i);
}
return result;
}
public static void main(String[] args) {
System.out.println(reverseLoop("Java"));
System.out.println(new StringBuilder("Java").reverse());
}
}
avaJ
avaJ
How it works
charAt(i)gives one character. The loop reads them from the end.StringBuilder.reverse()is the shortest way.
Read Java String Methods.
Check if a string is a palindrome
Description: A palindrome reads the same from both sides, like madam. Write isPalindrome(String s) which ignores the case and the spaces. Test it with “Madam”, “Nurses run” and “Java”.
Hint:
- Clean the text with
replace(" ", "")andtoLowerCase(), then compare it with its reverse.
Solution
public class Main {
static boolean isPalindrome(String s) {
String clean = s.replace(" ", "").toLowerCase();
String reversed = new StringBuilder(clean).reverse().toString();
return clean.equals(reversed);
}
public static void main(String[] args) {
for (String text : new String[]{"Madam", "Nurses run", "Java"}) {
System.out.println(text + " -> " + isPalindrome(text));
}
}
}
Madam -> true
Nurses run -> true
Java -> false
How it works
- We remove the spaces and use one case, so only the letters are compared.
equals()compares the text. Do not use==.
Read Java Strings.
Count the vowels in a string
Description: Count how many vowels (a, e, i, o, u) and how many consonants are in "Learn Java Programming".
Hint:
- Use
toCharArray(),Character.isLetter()andindexOfon the string"aeiou".
Solution
public class Main {
public static void main(String[] args) {
String text = "Learn Java Programming";
int vowels = 0, consonants = 0;
for (char c : text.toLowerCase().toCharArray()) {
if (!Character.isLetter(c)) continue; // skip the spaces
if ("aeiou".indexOf(c) >= 0) {
vowels++;
} else {
consonants++;
}
}
System.out.println("Vowels: " + vowels + ", consonants: " + consonants);
}
}
Vowels: 7, consonants: 13
How it works
"aeiou".indexOf(c)gives -1 when the letter is not a vowel.continueskips the spaces.
Read Java String Methods.
Find the second largest number in an array
Description: Find the second largest number in {12, 35, 1, 10, 34, 1} without sorting the array.
Hint:
- Keep two variables:
largestandsecond. Update both in one loop.
Solution
public class Main {
static int secondLargest(int[] a) {
int largest = Integer.MIN_VALUE, second = Integer.MIN_VALUE;
for (int n : a) {
if (n > largest) {
second = largest;
largest = n;
} else if (n > second && n != largest) {
second = n;
}
}
return second;
}
public static void main(String[] args) {
System.out.println(secondLargest(new int[]{12, 35, 1, 10, 34, 1}));
System.out.println(secondLargest(new int[]{5, 5, 5, 2}));
}
}
34
2
How it works
- When a new biggest value comes, the old biggest becomes the second.
n != largestignores the duplicates of the biggest value.
Read Java Arrays.
Sort an array with bubble sort
Description: Sort {64, 34, 25, 12, 22, 11, 90} in ascending order without using Arrays.sort(). Then check your answer with Arrays.sort().
Hint:
- Compare each pair of neighbours and swap them if they are in the wrong order. Repeat.
Solution
import java.util.Arrays;
public class Main {
static void bubbleSort(int[] a) {
for (int i = 0; i < a.length - 1; i++) {
boolean swapped = false;
for (int j = 0; j < a.length - 1 - i; j++) {
if (a[j] > a[j + 1]) {
int temp = a[j];
a[j] = a[j + 1];
a[j + 1] = temp;
swapped = true;
}
}
if (!swapped) break; // already sorted
}
}
public static void main(String[] args) {
int[] data = {64, 34, 25, 12, 22, 11, 90};
int[] check = data.clone();
bubbleSort(data);
Arrays.sort(check);
System.out.println(Arrays.toString(data));
System.out.println(Arrays.equals(data, check));
}
}
[11, 12, 22, 25, 34, 64, 90]
true
How it works
- After each round of the outer loop, the biggest remaining value goes to its place at the end.
- If a full round makes no swap, the array is sorted and we stop.
- Bubble sort is good to learn, but slow (O(n squared)). Real code uses
Arrays.sort().
Read Java Arrays.
Transpose a matrix
Description: Transpose the matrix {{1,2,3},{4,5,6}}. The result must be {{1,4},{2,5},{3,6}}.
Hint:
- The new matrix has
columnsrows androwscolumns. Copym[i][j]tot[j][i].
Solution
import java.util.Arrays;
public class Main {
static int[][] transpose(int[][] m) {
int rows = m.length, cols = m[0].length;
int[][] t = new int[cols][rows];
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
t[j][i] = m[i][j];
}
}
return t;
}
public static void main(String[] args) {
int[][] m = {{1, 2, 3}, {4, 5, 6}};
System.out.println(Arrays.deepToString(transpose(m)));
}
}
[[1, 4], [2, 5], [3, 6]]
How it works
- A 2 x 3 matrix becomes a 3 x 2 matrix, so a new array with the sizes swapped is needed.
Read Multidimensional Arrays.
Build a BankAccount class
Description: Create a class BankAccount with a private balance. Add deposit(amount) and withdraw(amount). Refuse a negative deposit and a withdraw bigger than the balance (throw an exception). Test it.
Hint:
- Keep the field
privateand give a getter only. - Throw
IllegalArgumentExceptionandIllegalStateException.
Solution
class BankAccount {
private double balance;
void deposit(double amount) {
if (amount <= 0) throw new IllegalArgumentException("Deposit must be positive");
balance += amount;
}
void withdraw(double amount) {
if (amount > balance) throw new IllegalStateException("Not enough balance");
balance -= amount;
}
double getBalance() { return balance; }
}
public class Main {
public static void main(String[] args) {
BankAccount acc = new BankAccount();
acc.deposit(1000);
acc.withdraw(250);
System.out.println(acc.getBalance());
try {
acc.withdraw(5000);
} catch (IllegalStateException e) {
System.out.println("Error: " + e.getMessage());
}
try {
acc.deposit(-5);
} catch (IllegalArgumentException e) {
System.out.println("Error: " + e.getMessage());
}
}
}
750.0
Error: Not enough balance
Error: Deposit must be positive
How it works
- The balance is private, so the only way to change it is through the two methods which check the values.
Read Java Encapsulation.
Calculate areas with inheritance and polymorphism
Description: Make an abstract class Shape with an abstract method area(). Write Circle and Rectangle which extend it. Put a circle (radius 2) and a rectangle (3 x 4) in one array and print the total area.
Hint:
- Use an array of type
Shape[].
Solution
abstract class Shape {
abstract double area();
}
class Circle extends Shape {
private final double r;
Circle(double r) { this.r = r; }
double area() { return Math.PI * r * r; }
}
class Rectangle extends Shape {
private final double w, h;
Rectangle(double w, double h) { this.w = w; this.h = h; }
double area() { return w * h; }
}
public class Main {
public static void main(String[] args) {
Shape[] shapes = { new Circle(2), new Rectangle(3, 4) };
double total = 0;
for (Shape s : shapes) {
total += s.area();
}
System.out.printf("Total area: %.2f%n", total);
}
}
Total area: 24.57
How it works
- The loop uses the type
Shape. Java calls thearea()of the real object (polymorphism). - You can add a new shape without changing the loop.
Read Polymorphism and Abstract Classes.
Sort a list of students with a Comparator
Description: You have students (name and marks). Sort them by marks, highest first. When the marks are equal, sort by name.
Hint:
- Use
Comparator.comparingInt(...).reversed()andthenComparing(...).
Solution
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
record Student(String name, int marks) { }
public class Main {
public static void main(String[] args) {
List<Student> list = new ArrayList<>(List.of(
new Student("Meera", 88), new Student("Aman", 95),
new Student("Riya", 88), new Student("Karan", 70)));
list.sort(Comparator.comparingInt(Student::marks).reversed()
.thenComparing(Student::name));
list.forEach(System.out::println);
}
}
Student[name=Aman, marks=95]
Student[name=Meera, marks=88]
Student[name=Riya, marks=88]
Student[name=Karan, marks=70]
How it works
comparingIntcompares by the marks, andreversed()makes it descending.thenComparingis used only when the first comparison says the values are equal.
Read Lambda Expressions.
Create a custom exception for an invalid age
Description: Create a checked exception InvalidAgeException. Write a method register(int age) which throws it when the age is below 18, and catch it in main.
Hint:
- Extend
Exception, and usethrowsin the method line.
Solution
class InvalidAgeException extends Exception {
InvalidAgeException(String message) {
super(message);
}
}
public class Main {
static void register(int age) throws InvalidAgeException {
if (age < 18) {
throw new InvalidAgeException("Age " + age + " is below 18");
}
System.out.println("Registered, age " + age);
}
public static void main(String[] args) {
for (int age : new int[]{25, 15}) {
try {
register(age);
} catch (InvalidAgeException e) {
System.out.println("Cannot register: " + e.getMessage());
}
}
}
}
Registered, age 25
Cannot register: Age 15 is below 18
How it works
- Because the class extends
Exception(notRuntimeException), it is checked: the compiler forces the caller to handle it.
Read Java Exceptions.
Count the frequency of words with a HashMap
Description: Count the words of "the cat and the dog and the bird". Print each word with its count, in alphabetical order.
Hint:
- Use a
TreeMap(sorted keys) andmerge(word, 1, Integer::sum).
Solution
import java.util.Map;
import java.util.TreeMap;
public class Main {
public static void main(String[] args) {
String text = "the cat and the dog and the bird";
Map<String, Integer> counts = new TreeMap<>();
for (String word : text.split(" ")) {
counts.merge(word, 1, Integer::sum);
}
counts.forEach((word, n) -> System.out.println(word + " = " + n));
}
}
and = 2
bird = 1
cat = 1
dog = 1
the = 3
How it works
mergeputs 1 if the word is new, or adds 1 to the old count.- A
TreeMapkeeps the keys sorted. AHashMapwould print them in any order.
Read Java HashMap.