PYnative

Python Programming

  • Learn Python ▼
    • Python Tutorials
    • Python Basics
    • Python Interview Q&As
  • Exercises ▼
    • Python Exercises
    • C++ Exercises
    • C Programming Exercises
    • Java Exercises
    • C# Exercises
  • Quizzes
  • Online Compilers▼
    • Online Python Code Editor
    • Online C Compiler
    • Online C++ Compiler
    • Online Java Compiler
    • Online C# Compiler
Home » Java Exercises » Basic Java Exercise for Beginners: 60+ Coding Problems with Solutions

Basic Java Exercise for Beginners: 60+ Coding Problems with Solutions

Updated on: July 8, 2026 | Leave a Comment

This collection of 64 basic Java coding exercises is built for absolute beginners who are just getting comfortable with the language’s syntax and core building blocks.

The exercises progress from simple variable and arithmetic operations through conditionals, loops, arrays, 2D arrays, strings, and finish with an introduction to methods and object-oriented programming.

Each exercise includes a Practice Problem, an Exercise Purpose, a Hint, and a Solution with a line-by-line Explanation, so you understand not just what the code does, but why it works.

  • Also, See: Java Exercises with over 20+ topic-wise sets and 575+ coding questions to practice.
  • Practice questions using our Online Java Compiler
+ Table of Contents (64 Exercises)

Table of contents

  • Exercise 1: Add Two Numbers
  • Exercise 2: Swap with Temp Variable
  • Exercise 3: Swap without Temp Variable
  • Exercise 4: Rectangle Area & Perimeter
  • Exercise 5: Simple Interest Calculator
  • Exercise 6: Compound Interest Calculator
  • Exercise 7: Square & Cube of a Number
  • Exercise 8: Even or Odd Checker
  • Exercise 9: Largest of Three Numbers
  • Exercise 10: Leap Year Checker
  • Exercise 11: Simple Calculator Using switch
  • Exercise 12: Print Numbers 1 to 100
  • Exercise 13: Sum of Natural Numbers Using a While Loop
  • Exercise 14: Print Numbers Divisible by 3 or 5 Using Continue
  • Exercise 15: Print Even Numbers Using a Do-While Loop
  • Exercise 16: Multiplication Table
  • Exercise 17: Factorial of a Number
  • Exercise 18: Fibonacci Series
  • Exercise 19: Reverse a Number
  • Exercise 20: Sum of Digits
  • Exercise 21: Prime Number Checker
  • Exercise 22: Armstrong Number Checker
  • Exercise 23: Star Triangle Pattern
  • Exercise 24: Print Array Elements
  • Exercise 25: Array Sum and Average
  • Exercise 26: Find Min and Max in Array
  • Exercise 27: Reverse an Array
  • Exercise 28: Bubble Sort
  • Exercise 29: Find Duplicate Elements
  • Exercise 30: Merge Two Arrays
  • Exercise 31: Matrix Addition
  • Exercise 32: String Length (Manual Count)
  • Exercise 33: Palindrome String Checker
  • Exercise 34: Uppercase & Lowercase Conversion
  • Exercise 35: Remove Spaces from String
  • Exercise 36: Character Frequency Counter
  • Exercise 37: String Anagrams
  • Exercise 38: Custom Method: isEven
  • Exercise 39: Class and Object Basics
  • Exercise 40: Constructors in Java
  • Exercise 41: Method Overloading
  • Exercise 42: Encapsulation with BankAccount
  • Exercise 43: Demonstrate Inheritance with an Animal and Dog Class
  • Exercise 44: Demonstrate Method Overriding (Runtime Polymorphism)
  • Exercise 45: Demonstrate Static Variables and Static Methods
  • Exercise 46: Create and Print an ArrayList of Integers
  • Exercise 47: Add, Remove, and Search Elements in an ArrayList
  • Exercise 48: Sort an ArrayList of Strings Alphabetically
  • Exercise 49: Create a HashMap and Iterate Over Its Key-Value Pairs
  • Exercise 50: Count Word Frequency in a Sentence Using HashMap
  • Exercise 51: Remove Duplicate Elements from an ArrayList
  • Exercise 52: Sort a HashMap by Its Values
  • Exercise 53: Create a TreeMap and Print Keys in Sorted Order
  • Exercise 54: Check if a Key Exists in a HashMap Using containsKey()
  • Exercise 55: Remove Duplicate Elements from an Array Using HashSet
  • Exercise 56: Store and Print Unique Elements in Sorted Order Using TreeSet
  • Exercise 57: Find Common Elements Between Two Sets Using HashSet
  • Exercise 58: Get and Print the Current Date and Time
  • Exercise 59: Calculate the Difference Between Two Dates
  • Exercise 60: Add or Subtract Days from a Given Date
  • Exercise 61: Format a Date Using DateTimeFormatter
  • Exercise 62: Write Text to a File Using FileWriter
  • Exercise 63: Read Content from a File Using BufferedReader
  • Exercise 64: Append Data to an Existing File

Exercise 1: Add Two Numbers

Practice Problem: Write a program that takes two numbers as input and prints their sum.

Exercise Purpose: To practice reading user input with the Scanner class and performing basic arithmetic operations in Java.

Given Input: a = 12, b = 28

Expected Output: Sum = 40

▼ Hint
  • Use Scanner sc = new Scanner(System.in); to read values from the user.
  • Read each number with sc.nextInt() and store them in separate integer variables before adding them together.
▼ Solution and Explanation:
import java.util.Scanner;

public class Main{
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);

        System.out.print("Enter first number: ");
        int a = sc.nextInt();

        System.out.print("Enter second number: ");
        int b = sc.nextInt();

        int sum = a + b;
        System.out.println("Sum = " + sum);
    }
}Code language: Java (java)

Explanation:

  • import java.util.Scanner: This imports the Scanner class, which allows the program to read input from the keyboard.
  • sc.nextInt(): Reads the next integer the user types and stores it in the variable.
  • int sum = a + b: Adds the two integers together and stores the result in a new variable called sum.
  • System.out.println("Sum = " + sum): Prints the result to the console with a descriptive label.

Exercise 2: Swap with Temp Variable

Practice Problem: Write a program that swaps the values of two variables using a third temporary variable and prints the result.

Exercise Purpose: To understand how data is stored in variables and how a temporary holding variable can be used to exchange values between two variables without losing data.

Given Input: a = 5, b = 10

Expected Output:

Before swap: a = 5, b = 10
After swap:  a = 10, b = 5
▼ Hint
  • Declare a third variable temp and save the value of a into it before overwriting a.
  • The swap takes three steps: temp = a, then a = b, then b = temp.
▼ Solution and Explanation:
public class Main {
    public static void main(String[] args) {
        int a = 5, b = 10;

        System.out.println("Before swap: a = " + a + ", b = " + b);

        int temp = a;
        a = b;
        b = temp;

        System.out.println("After swap:  a = " + a + ", b = " + b);
    }
}Code language: Java (java)

Explanation:

  • int temp = a: The original value of a is saved in temp so it is not lost in the next step.
  • a = b: The value of b is copied into a, overwriting its original value.
  • b = temp: The original value of a, which was safely stored in temp, is now assigned to b, completing the swap.

Exercise 3: Swap without Temp Variable

Practice Problem: Write a program that swaps the values of two integer variables without using a third temporary variable, relying only on arithmetic operations.

Exercise Purpose: To explore an alternative swapping technique that uses addition and subtraction instead of extra memory, deepening understanding of how arithmetic can manipulate variable state.

Given Input: a = 5, b = 10

Expected Output:

Before swap: a = 5, b = 10
After swap:  a = 10, b = 5
▼ Hint
  • Add both values together and store the result in a: a = a + b.
  • You can then recover the original value of a by subtracting: b = a - b, and finally a = a - b.
▼ Solution and Explanation:
public class Main {
    public static void main(String[] args) {
        int a = 5, b = 10;

        System.out.println("Before swap: a = " + a + ", b = " + b);

        a = a + b; // a = 15
        b = a - b; // b = 5  (original a)
        a = a - b; // a = 10 (original b)

        System.out.println("After swap:  a = " + a + ", b = " + b);
    }
}Code language: Java (java)

Explanation:

  • a = a + b: a now holds the combined sum of both original values (15). The original value of a is encoded inside this sum.
  • b = a - b: Subtracting the current b from the sum extracts the original value of a (15 – 10 = 5) and assigns it to b.
  • a = a - b: Subtracting the newly updated b from a extracts the original value of b (15 – 5 = 10) and assigns it to a, completing the swap.

Exercise 4: Rectangle Area & Perimeter

Practice Problem: Write a program that takes the length and width of a rectangle as input and calculates and prints both its area and its perimeter.

Exercise Purpose: To practice using variables in multiple arithmetic formulas within the same program and to reinforce formatted output with descriptive labels.

Given Input: length = 8, width = 5

Expected Output:

Area      = 40
Perimeter = 26
▼ Hint
  • Area of a rectangle: length * width.
  • Perimeter of a rectangle: 2 * (length + width).
▼ Solution and Explanation:
public class Main {
    public static void main(String[] args) {
        int length = 8;
        int width  = 5;

        int area      = length * width;
        int perimeter = 2 * (length + width);

        System.out.println("Area      = " + area);
        System.out.println("Perimeter = " + perimeter);
    }
}Code language: Java (java)

Explanation:

  • int area = length * width: Multiplies the two dimensions to get the total surface enclosed by the rectangle.
  • int perimeter = 2 * (length + width): Adds the length and width first (getting one pair of sides), then doubles it to account for all four sides.
  • Both results are printed on separate lines with aligned labels for clarity.

Exercise 5: Simple Interest Calculator

Practice Problem: Write a program that calculates simple interest given a principal amount, an annual interest rate, and a time period in years.

Exercise Purpose: To practice working with double (decimal) variables and applying a real-world mathematical formula in code.

Given Input: principal = 1000.0, rate = 5.0, time = 3

Expected Output: Simple Interest = 150.0

▼ Hint
  • The formula for simple interest is: SI = (principal * rate * time) / 100.
  • Use double instead of int for your variables so that decimal values are handled correctly.
▼ Solution and Explanation:
public class Main {
    public static void main(String[] args) {
        double principal = 1000.0;
        double rate      = 5.0;
        int    time      = 3;

        double si = (principal * rate * time) / 100;

        System.out.println("Simple Interest = " + si);
    }
}Code language: Java (java)

Explanation:

  • double principal = 1000.0: Declares the starting amount as a decimal-capable type to avoid integer division errors.
  • (principal * rate * time) / 100: Applies the standard simple interest formula. The division by 100 converts the percentage rate into a decimal fraction before multiplying.
  • System.out.println("Simple Interest = " + si): Prints the calculated interest with a clear label.

Exercise 6: Compound Interest Calculator

Practice Problem: Write a program that calculates compound interest given a principal, an annual interest rate, and a number of years.

Exercise Purpose: To learn how to use Math.pow() from Java’s built-in Math library and to understand the difference between simple and compound growth.

Given Input: principal = 1000.0, rate = 5.0, time = 3

Expected Output:

Amount after interest = 1157.625
Compound Interest     = 157.625
▼ Hint
  • The compound interest formula is: A = principal * Math.pow((1 + rate / 100), time).
  • The compound interest itself is just the total amount minus the original principal: CI = A - principal.
▼ Solution and Explanation:
public class Main {
    public static void main(String[] args) {
        double principal = 1000.0;
        double rate      = 5.0;
        int    time      = 3;

        double amount = principal * Math.pow((1 + rate / 100), time);
        double ci     = amount - principal;

        System.out.println("Amount after interest = " + amount);
        System.out.println("Compound Interest     = " + ci);
    }
}Code language: Java (java)

Explanation:

  • rate / 100: Converts the percentage rate (5.0) into its decimal equivalent (0.05) for use in the formula.
  • Math.pow(base, exponent): A built-in Java method that raises the base to the power of the exponent, used here to apply compounding over each year.
  • double ci = amount - principal: Isolates just the interest earned by subtracting the original principal from the total accumulated amount.

Exercise 7: Square & Cube of a Number

Practice Problem: Write a program that takes a number as input and prints both its square and its cube.

Exercise Purpose: To practice performing repeated multiplication on a variable and to get familiar with using Math.pow() as an alternative to manual multiplication.

Given Input: num = 4

Expected Output:

Square of 4 = 16
Cube of 4   = 64
▼ Hint
  • Square: multiply the number by itself: num * num.
  • Cube: multiply it by itself three times: num * num * num, or use Math.pow(num, 3).
▼ Solution and Explanation:
public class Main {
    public static void main(String[] args) {
        int num = 4;

        int square = num * num;
        int cube   = num * num * num;

        System.out.println("Square of " + num + " = " + square);
        System.out.println("Cube of "   + num + " = " + cube);
    }
}Code language: Java (java)

Explanation:

  • int square = num * num: Multiplies the number by itself once to produce the second power (4 x 4 = 16).
  • int cube = num * num * num: Multiplies the number by itself twice more to produce the third power (4 x 4 x 4 = 64).
  • Both values are printed with the original number embedded in the label so the output is self-explanatory.

Exercise 8: Even or Odd Checker

Practice Problem: Write a program that reads an integer from the user and prints whether it is even or odd.

Exercise Purpose: To learn how to use the modulo operator % and an if-else statement to make a decision based on a condition.

Given Input: num = 7

Expected Output: 7 is Odd

▼ Hint
  • A number is even if dividing it by 2 leaves no remainder. Use the modulo operator: num % 2 == 0.
  • Use an if-else block to print a different message depending on whether the condition is true or false.
▼ Solution and Explanation:
import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        int num = 7;

        if (num % 2 == 0) {
            System.out.println(num + " is Even");
        } else {
            System.out.println(num + " is Odd");
        }
    }
}Code language: Java (java)

Explanation:

  • num % 2: The modulo operator returns the remainder after dividing num by 2. A result of 0 means there is no remainder, so the number is even.
  • if (num % 2 == 0): The condition evaluates to true for even numbers, routing execution to the first print statement.
  • else: If the condition is false (remainder is 1), execution falls through to the second print statement, labelling the number as odd.

Exercise 9: Largest of Three Numbers

Practice Problem: Write a program that reads three integers from the user and prints the largest among them.

Exercise Purpose: To practice chaining if-else if-else conditions to compare multiple values and identify an extremum.

Given Input: a = 14, b = 37, c = 22

Expected Output: Largest = 37

▼ Hint
  • Check if a is greater than both b and c using the && (AND) operator: a > b && a > c.
  • Use else if to then check b, and let the final else handle the case where c is the largest.
▼ Solution and Explanation:
import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        int a = 14, b = 37, c = 22;

        if (a >= b && a >= c) {
            System.out.println("Largest = " + a);
        } else if (b >= a && b >= c) {
            System.out.println("Largest = " + b);
        } else {
            System.out.println("Largest = " + c);
        }
    }
}Code language: Java (java)

Explanation:

  • a >= b && a >= c: Both comparisons must be true at the same time for a to be the largest. The && operator ensures both conditions are checked together.
  • else if (b >= a && b >= c): Only reached if a is not the largest. It then checks whether b wins the comparison against both remaining values.
  • else: If neither a nor b passed their checks, c must be the largest, so it is printed without any further condition needed.

Exercise 10: Leap Year Checker

Practice Problem: Write a program that reads a year from the user and determines whether it is a leap year.

Exercise Purpose: To practice combining multiple conditions with && and || operators to implement a real-world rule that has more than one criterion.

Given Input: year = 2024

Expected Output: 2024 is a Leap Year

▼ Hint
  • A year is a leap year if it is divisible by 4, except for century years (divisible by 100), which must also be divisible by 400.
  • The full condition in code: (year % 4 == 0 && year % 100 != 0) || (year % 400 == 0).
▼ Solution and Explanation:
import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        int year = 2024;

        boolean isLeap = (year % 4 == 0 && year % 100 != 0) || (year % 400 == 0);

        if (isLeap) {
            System.out.println(year + " is a Leap Year");
        } else {
            System.out.println(year + " is not a Leap Year");
        }
    }
}Code language: Java (java)

Explanation:

  • year % 4 == 0 && year % 100 != 0: Catches ordinary leap years – divisible by 4 but not a century year (e.g., 2024).
  • year % 400 == 0: The exception for century years – 400, 800, and 2000 are leap years even though they are divisible by 100.
  • boolean isLeap: Storing the result in a named boolean variable makes the if statement cleaner and the logic easier to read at a glance.

Exercise 11: Simple Calculator Using switch

Practice Problem: Write a program that reads two numbers and an operator (+, -, *, /) from the user and prints the result of the chosen operation.

Exercise Purpose: To learn the switch statement as a cleaner alternative to a long chain of if-else if blocks when branching on a single value.

Given Input: a = 10, b = 4, operator = *

Expected Output: Result = 40.0

▼ Hint
  • Read the operator as a char using sc.next().charAt(0) to capture a single character from user input.
  • Use a switch statement on the operator character, with one case per operation and a default case for invalid input.
▼ Solution and Explanation:
import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);

        System.out.print("Enter first number:  ");
        double a = sc.nextDouble();

        System.out.print("Enter second number: ");
        double b = sc.nextDouble();

        System.out.print("Enter operator (+, -, *, /): ");
        char op = sc.next().charAt(0);

        double result;

        switch (op) {
            case '+': result = a + b; break;
            case '-': result = a - b; break;
            case '*': result = a * b; break;
            case '/':
                if (b != 0) {
                    result = a / b;
                } else {
                    System.out.println("Error: Division by zero.");
                    return;
                }
                break;
            default:
                System.out.println("Error: Unknown operator.");
                return;
        }

        System.out.println("Result = " + result);
    }
}Code language: Java (java)

Explanation:

  • sc.next().charAt(0): Reads the next token from input as a String, then extracts only its first character as a char for use in the switch.
  • switch (op): Compares the operator character against each case label in order. When a match is found, that block runs and break exits the switch.
  • if (b != 0) inside the division case: Guards against dividing by zero, which would cause a runtime error. The program exits early with an error message if b is zero.
  • default: Catches any character that does not match the four valid operators, giving the user meaningful feedback instead of silently producing a wrong answer.

Exercise 12: Print Numbers 1 to 100

Practice Problem: Write a program that prints all integers from 1 to 100 on a single line, separated by spaces.

Exercise Purpose: To learn the fundamental syntax and control flow of a for loop, including loop initialization, the exit condition, and the increment step.

Given Input: (None)

Expected Output: 1 2 3 4 5 ... 98 99 100

▼ Hint
  • A for loop typically has three components: for(initialization; condition; update).
  • Use System.out.print() instead of println() to keep everything on one line.
▼ Solution and Explanation:
public class Main {
    public static void main(String[] args) {
        for (int i = 1; i <= 100; i++) {
            System.out.print(i + " ");
        }
    }
}Code language: Java (java)

Explanation:

  • int i = 1: The loop variable is initialised to 1, which is the first number to print.
  • i <= 100: The loop continues running as long as this condition is true. Once i becomes 101, the condition fails and the loop stops.
  • i++: After each iteration, i is incremented by 1, advancing to the next number.
  • System.out.print(i + " "): Prints the current number followed by a space, without moving to a new line, so all 100 numbers appear on the same line.

Exercise 13: Sum of Natural Numbers Using a While Loop

Practice Problem: Write a Java program to calculate the sum of the first N natural numbers using a while loop.

Purpose: This exercise helps you practice the while loop structure and the accumulator pattern, a foundational technique used in iterative algorithms and running totals.

Given Input: n = 10

Expected Output: Sum = 55

💡 Hint
  • Initialize sum = 0 and a counter i = 1 before the loop.
  • Use a while loop that runs while i <= n.
  • Add i to sum on each iteration and then increment i.
  • Print sum after the loop ends.
✅ Solution & Explanation

Solution:

public class Main {
    public static void main(String[] args) {
        int n = 10;
        int sum = 0;
        int i = 1;

        while (i <= n) {
            sum += i;
            i++;
        }

        System.out.println("Sum = " + sum);
    }
}Code language: Java (java)

Explanation:

  • int sum = 0: Initializes a variable to store the running total before the loop starts.
  • while (i <= n): Repeats the loop as long as the counter i is less than or equal to n.
  • sum += i: Adds the current value of i to sum on every iteration.
  • i++: Increments the counter so the loop eventually terminates, avoiding an infinite loop.

Exercise 14: Print Numbers Divisible by 3 or 5 Using Continue

Practice Problem: Write a Java program to print all numbers from 1 to N that are divisible by 3 or 5, skipping the rest using the continue statement.

Purpose: This exercise helps you practice using continue to skip loop iterations and combine it with conditional logic and the modulo operator, a common pattern for filtering values in a loop.

Given Input: n = 20

Expected Output:

3
5
6
9
10
12
15
18
20
▼ Hint
  • Loop from 1 to n using a for loop.
  • Inside the loop, check if the number is NOT divisible by 3 or 5.
  • If it is not divisible, use continue to skip to the next iteration.
  • Otherwise, print the number.
▼ Solution & Explanation

Solution:

public class Main {
    public static void main(String[] args) {
        int n = 20;

        for (int i = 1; i <= n; i++) {
            if (i % 3 != 0 && i % 5 != 0) {
                continue;
            }
            System.out.println(i);
        }
    }
}Code language: Java (java)

Explanation:

  • i % 3 != 0 && i % 5 != 0: Checks whether the number is divisible by neither 3 nor 5.
  • continue: Skips the rest of the current iteration and moves to the next value of i without printing.
  • System.out.println(i): Runs only when the number passes the divisibility check, printing it to the console.

Exercise 15: Print Even Numbers Using a Do-While Loop

Practice Problem: Write a Java program to print all even numbers from 1 to N using a do-while loop.

Purpose: This exercise helps you practice the do-while loop structure, which guarantees at least one execution, and reinforces checking even numbers using the modulo operator.

Given Input: n = 10

Expected Output:

2
4
6
8
10
▼ Hint
  • Initialize a counter i = 1.
  • Use a do-while loop so the block runs before the condition is tested.
  • Inside the loop, check if i is even using i % 2 == 0.
  • Increment i after each check and continue while i <= n.
▼ Solution & Explanation

Solution:

public class Main {
    public static void main(String[] args) {
        int n = 10;
        int i = 1;

        do {
            if (i % 2 == 0) {
                System.out.println(i);
            }
            i++;
        } while (i <= n);
    }
}Code language: Java (java)

Explanation:

  • do { ... } while (i <= n): Executes the loop body first, then checks the condition, guaranteeing at least one run.
  • i % 2 == 0: Checks whether the current number is even by testing if it leaves no remainder when divided by 2.
  • i++: Increments the counter before the condition is re-checked at the end of the loop.

Exercise 16: Multiplication Table

Practice Problem: Write a program that reads a number from the user and prints its multiplication table from 1 to 10.

Exercise Purpose: To practice looping through a fixed range and using the loop counter as a multiplier in a formatted output statement.

Given Input: num = 7

Expected Output:

7 x 1  = 7
7 x 2  = 14
...
7 x 10 = 70
▼ Hint
  • Declare your target number as a variable before the loop starts.
  • Inside the loop, multiply that number by the loop counter i and print the formatted equation on each iteration.
▼ Solution and Explanation:
public class Main {
    public static void main(String[] args) {
        int num = 7;
        for (int i = 1; i <= 10; i++) {
            int product = num * i;
            System.out.println(num + " x " + i + " = " + product);
        }
    }
}Code language: Java (java)

Explanation:

  • for (int i = 1; i <= 10; i++): The loop runs exactly 10 times, with i taking the values 1 through 10 – one for each row of the table.
  • int product = num * i: On every iteration, the target number is multiplied by the current value of the loop counter to produce the result for that row.
  • System.out.println(...): Prints each row of the table as a formatted equation, moving to a new line after each one.

Exercise 17: Factorial of a Number

Practice Problem: Write a program that reads a non-negative integer from the user and prints its factorial.

Exercise Purpose: To practice using a loop to accumulate a running product, and to understand how a result is built up incrementally across multiple iterations.

Given Input: n = 6

Expected Output: Factorial of 6 = 720

▼ Hint
  • Start with a variable factorial = 1 (not 0, since multiplying by 0 would always give 0).
  • Loop from 1 to n and multiply factorial by the loop counter on each step: factorial *= i.
▼ Solution and Explanation:
public class Main {
    public static void main(String[] args) {
        int n = 6;
        long factorial = 1;
        for (int i = 1; i <= n; i++) {
            factorial *= i;
        }
        System.out.println("Factorial of " + n + " = " + factorial);
    }
}Code language: Java (java)

Explanation:

  • long factorial = 1: long is used instead of int because factorials grow very quickly – 13! already exceeds the maximum value of an int.
  • factorial *= i: A shorthand for factorial = factorial * i. On each iteration, the running product is multiplied by the next integer in the sequence.
  • After the loop finishes, factorial holds the product of all integers from 1 to n, which is the definition of n factorial (n!).

Exercise 18: Fibonacci Series

Practice Problem: Write a program that reads a number n from the user and prints the first n terms of the Fibonacci series.

Exercise Purpose: To practice maintaining and updating multiple variables inside a loop to produce a sequence where each term depends on the two that came before it.

Given Input: n = 8

Expected Output: 0 1 1 2 3 5 8 13

▼ Hint
  • Start with two variables: a = 0 and b = 1. On each loop iteration, print a, then advance the sequence by setting a = b and b = a + b.
  • Be careful with the order of updates: save a + b in a temporary variable first, or you will overwrite a before you can use it to update b.
▼ Solution and Explanation:
public class Main {
    public static void main(String[] args) {
        int n = 8;
        int a = 0, b = 1;
        for (int i = 0; i < n; i++) {
            System.out.print(a + " ");
            int next = a + b;
            a = b;
            b = next;
        }
    }
}Code language: Java (java)

Explanation:

  • int a = 0, b = 1: These two variables represent the current and next term of the sequence. The series always starts with 0 and 1.
  • int next = a + b: The sum of the two current terms gives the next term in the series. It is stored in a temporary variable before either a or b is overwritten.
  • a = b; b = next: Both variables slide forward by one position: a takes the old value of b, and b takes the newly computed next term, ready for the following iteration.

Exercise 19: Reverse a Number

Practice Problem: Write a program that reads an integer and prints it with its digits in reverse order (e.g., 123 becomes 321).

Exercise Purpose: To practice extracting individual digits from a number using the modulo and integer division operators inside a while loop.

Given Input: num = 4892

Expected Output: Reversed = 2984

▼ Hint
  • Use num % 10 to peel off the last digit of the number on each loop iteration.
  • Build the reversed number by shifting the running result left one place: reversed = reversed * 10 + digit, then remove the last digit with num /= 10.
▼ Solution and Explanation:
public class Main {
    public static void main(String[] args) {
        int num = 4892;

        int reversed = 0;

        while (num != 0) {
            int digit = num % 10;
            reversed  = reversed * 10 + digit;
            num      /= 10;
        }

        System.out.println("Reversed = " + reversed);
    }
}Code language: Java (java)

Explanation:

  • int digit = num % 10: The modulo operation extracts the rightmost digit of the current number. For 4892, the first digit extracted is 2.
  • reversed = reversed * 10 + digit: Shifts all previously collected digits one place to the left (by multiplying by 10) and appends the newly extracted digit on the right, building the reversed number from left to right.
  • num /= 10: Integer division drops the last digit from num. The loop continues until num reaches 0, meaning all digits have been processed.

Exercise 20: Sum of Digits

Practice Problem: Write a program that reads an integer and prints the sum of all its individual digits (e.g., 493 gives 4 + 9 + 3 = 16).

Exercise Purpose: To reinforce the digit-extraction technique from the previous exercise, this time accumulating a running total instead of building a new number.

Given Input: num = 4931

Expected Output: Sum of digits = 17

▼ Hint
  • Use num % 10 to extract the last digit, add it to a running sum, then remove it with num /= 10.
  • Repeat this inside a while loop until num becomes 0.
▼ Solution and Explanation:
public class Main {
    public static void main(String[] args) {
        int num = 4931;

        int sum = 0;

        while (num != 0) {
            sum += num % 10;
            num /= 10;
        }

        System.out.println("Sum of digits = " + sum);
    }
}Code language: Java (java)

Explanation:

  • int sum = 0: The accumulator starts at zero so that the first digit added gives the correct running total.
  • sum += num % 10: Extracts the last digit with % 10 and immediately adds it to the running sum in a single step.
  • num /= 10: Drops the digit that was just processed by performing integer division, shrinking the number by one digit each iteration until nothing remains.

Exercise 21: Prime Number Checker

Practice Problem: Write a program that reads a positive integer and determines whether it is a prime number.

Exercise Purpose: To practice using a for loop with an early-exit break and a boolean flag to test a condition across multiple iterations before reaching a conclusion.

Given Input: num = 29

Expected Output: 29 is a Prime Number

▼ Hint
  • A prime number has no divisors other than 1 and itself. Loop from 2 up to num / 2 and check if any value divides num evenly using num % i == 0.
  • Use a boolean flag isPrime = true before the loop. If a divisor is found, set it to false and break out early.
▼ Solution and Explanation:
public class Main {
    public static void main(String[] args) {
        int num = 29;
        boolean isPrime = true;
        if (num < 2) {
            isPrime = false;
        } else {
            for (int i = 2; i <= num / 2; i++) {
                if (num % i == 0) {
                    isPrime = false;
                    break;
                }
            }
        }
        if (isPrime) {
            System.out.println(num + " is a Prime Number");
        } else {
            System.out.println(num + " is not a Prime Number");
        }
    }
}Code language: Java (java)

Explanation:

  • if (num < 2): Numbers less than 2 (including 0 and 1) are never prime by definition, so the flag is set to false immediately without entering the loop.
  • i <= num / 2: No divisor of a number can be larger than half of it (other than the number itself), so the loop only needs to check up to that point, saving unnecessary iterations.
  • num % i == 0: If the remainder is zero, i divides num evenly, which means num has a factor other than 1 and itself – so it cannot be prime.
  • break: As soon as one divisor is found, there is no need to keep checking. break exits the loop early, making the program more efficient.

Exercise 22: Armstrong Number Checker

Practice Problem: Write a program that checks whether a given number is an Armstrong number. A number is Armstrong if the sum of its digits each raised to the power of the total number of digits equals the number itself (e.g., 153 = 1³ + 5³ + 3³).

Exercise Purpose: To combine digit extraction from a while loop with Math.pow(), and to practice counting digits before using that count in a calculation.

Given Input: num = 153

Expected Output: 153 is an Armstrong Number

▼ Hint
  • First, count the number of digits by converting the number to a String: String.valueOf(num).length(), or by dividing in a loop.
  • Then extract each digit with num % 10, raise it to the power of the digit count using Math.pow(digit, digits), add it to a running sum, and compare the final sum to the original number.
▼ Solution and Explanation:
public class Main {
    public static void main(String[] args) {
        int num = 153;

        int digits = String.valueOf(num).length();
        int sum    = 0;
        int temp   = num;

        while (temp != 0) {
            int digit = temp % 10;
            sum      += (int) Math.pow(digit, digits);
            temp     /= 10;
        }

        if (sum == num) {
            System.out.println(num + " is an Armstrong Number");
        } else {
            System.out.println(num + " is not an Armstrong Number");
        }
    }
}Code language: Java (java)

Explanation:

  • String.valueOf(num).length(): Converts the number to its string representation and measures its length to determine how many digits it has – this count is used as the exponent.
  • int temp = num: A copy of the original number is used for digit extraction so the original value of num is preserved for the final comparison.
  • Math.pow(digit, digits): Raises each extracted digit to the power equal to the total number of digits (3 for a 3-digit number, 4 for a 4-digit number, and so on).
  • sum == num: If the accumulated sum of powered digits matches the original number exactly, the number is Armstrong.

Exercise 23: Star Triangle Pattern

Practice Problem: Write a program that reads a number n and prints a right-angled triangle made of asterisks, where row i contains i stars.

Exercise Purpose: To learn how to use nested loops – an outer loop to control the rows and an inner loop to control how many characters are printed on each row.

Given Input: n = 5

Expected Output:

*
* *
* * *
* * * *
* * * * *
▼ Hint
  • Use an outer for loop from 1 to n to handle each row.
  • Inside it, use an inner for loop from 1 to i (the current row number) to print the correct number of stars on that row, then call System.out.println() after the inner loop to move to the next line.
▼ Solution and Explanation:
import java.util.Scanner;
public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.print("Enter number of rows: ");
        int n = sc.nextInt();
        for (int i = 1; i <= n; i++) {
            for (int j = 1; j <= i; j++) {
                System.out.print("* ");
            }
            System.out.println();
        }
    }
}Code language: Java (java)

Explanation:

  • for (int i = 1; i <= n; i++): The outer loop runs once for each row. The variable i represents both the current row number and the number of stars that row should contain.
  • for (int j = 1; j <= i; j++): The inner loop runs i times per row, printing one star per iteration. Because the upper limit of the inner loop is i, each row gets exactly one more star than the previous one.
  • System.out.println(): Called after the inner loop finishes each row, this moves the cursor to the next line so the next row starts fresh below.

Exercise 24: Print Array Elements

Practice Problem: Write a program that declares and initializes an integer array, then iterates through it and prints each element on a single line separated by spaces.

Exercise Purpose: To learn how to declare and initialize an array in Java, access elements by index, and traverse the entire array using both a standard for loop and an enhanced for-each loop.

Given Input: arr = {10, 20, 30, 40, 50}

Expected Output: 10 20 30 40 50

▼ Hint
  • Declare an array with int[] arr = {10, 20, 30, 40, 50}; – the values are placed directly inside curly braces.
  • Use arr.length as the upper bound in your loop condition to avoid hardcoding the array size.
▼ Solution and Explanation:
public class Main {
    public static void main(String[] args) {
        int[] arr = {10, 20, 30, 40, 50};
        // Using a standard for loop
        for (int i = 0; i < arr.length; i++) {
            System.out.print(arr[i] + " ");
        }
        System.out.println(); // move to next line
        // Using an enhanced for-each loop
        for (int num : arr) {
            System.out.print(num + " ");
        }
    }
}Code language: Java (java)

Explanation:

  • int[] arr = {10, 20, 30, 40, 50}: Declares an integer array and initializes it with five values in one line using an array initializer block.
  • arr.length: A built-in property that returns the number of elements in the array. Using it instead of a hardcoded number means the loop still works correctly if the array is later changed to have more or fewer elements.
  • arr[i]: Accesses the element at position i. Array indices in Java start at 0, so the first element is arr[0] and the last is arr[arr.length - 1].
  • for (int num : arr): The enhanced for-each loop is a cleaner alternative when you only need the values and do not need the index. It reads as “for each integer num in arr“.

Exercise 25: Array Sum and Average

Practice Problem: Write a program that calculates and prints both the sum and the average of all elements in an integer array.

Exercise Purpose: To practice accumulating a running total across an array and performing a final calculation after the loop, while also handling the integer-to-decimal conversion needed for an accurate average.

Given Input: arr = {10, 20, 30, 40, 50}

Expected Output:

Sum     = 150
Average = 30.0
▼ Hint
  • Initialise int sum = 0 before the loop and add each element to it inside the loop.
  • To get a decimal average, cast either the sum or the length to double before dividing: (double) sum / arr.length.
▼ Solution and Explanation:
public class Main {
    public static void main(String[] args) {
        int[] arr = {10, 20, 30, 40, 50};

        int sum = 0;

        for (int num : arr) {
            sum += num;
        }

        double average = (double) sum / arr.length;

        System.out.println("Sum     = " + sum);
        System.out.println("Average = " + average);
    }
}Code language: Java (java)

Explanation:

  • int sum = 0: The accumulator starts at zero. Each element from the array is added to it during the loop, building up the total progressively.
  • sum += num: Shorthand for sum = sum + num. On each iteration, the current element is folded into the running total.
  • (double) sum / arr.length: Without the cast, dividing two integers in Java performs integer division and discards any decimal remainder. Casting sum to double first forces floating-point division, giving an accurate average.

Exercise 26: Find Min and Max in Array

Practice Problem: Write a program that finds and prints both the smallest and the largest elements in an integer array.

Exercise Purpose: To practice initializing tracker variables to the first element of an array and updating them conditionally as you scan through the remaining elements.

Given Input: arr = {34, 7, 23, 89, 12, 55}

Expected Output:

Minimum = 7
Maximum = 89
▼ Hint
  • Set both min and max to arr[0] before the loop – this gives a real value from the array to compare against, rather than an arbitrary number like 0 or 999.
  • Inside the loop, update min if the current element is smaller, and update max if it is larger.
▼ Solution and Explanation:
public class Main {
    public static void main(String[] args) {
        int[] arr = {34, 7, 23, 89, 12, 55};
        int min = arr[0];
        int max = arr[0];
        for (int i = 1; i < arr.length; i++) {
            if (arr[i] < min) min = arr[i];
            if (arr[i] > max) max = arr[i];
        }
        System.out.println("Minimum = " + min);
        System.out.println("Maximum = " + max);
    }
}Code language: Java (java)

Explanation:

  • int min = arr[0]; int max = arr[0]: Both trackers are seeded with the first element. This guarantees they hold a valid array value before any comparisons begin, and the loop then starts from index 1 since index 0 is already accounted for.
  • if (arr[i] < min) min = arr[i]: Each element is compared to the current minimum. If a smaller value is found, it becomes the new minimum.
  • if (arr[i] > max) max = arr[i]: The same pattern applies for the maximum. Both checks run independently on every element, so a single pass through the array is all that is needed.

Exercise 27: Reverse an Array

Practice Problem: Write a program that reverses the elements of an integer array in place (without creating a second array) and prints the result.

Exercise Purpose: To apply the temp-variable swap technique from Exercise 2 inside an array context, and to understand how two-pointer indices moving toward each other can process a data structure symmetrically.

Given Input: arr = {1, 2, 3, 4, 5}

Expected Output: 5 4 3 2 1

▼ Hint
  • Use two index variables – one starting at the left (left = 0) and one at the right (right = arr.length - 1). Swap the elements at those positions, then move both pointers inward.
  • Stop when left >= right – at that point, every pair has been swapped and the array is fully reversed.
▼ Solution and Explanation:
public class Main {
    public static void main(String[] args) {
        int[] arr = {1, 2, 3, 4, 5};
        int left  = 0;
        int right = arr.length - 1;
        while (left < right) {
            int temp    = arr[left];
            arr[left]   = arr[right];
            arr[right]  = temp;
            left++;
            right--;
        }
        for (int num : arr) {
            System.out.print(num + " ");
        }
    }
}Code language: Java (java)

Explanation:

  • int left = 0; int right = arr.length - 1: Two pointers start at opposite ends of the array. They will work their way toward the center, one swap at a time.
  • int temp = arr[left]; arr[left] = arr[right]; arr[right] = temp: The standard three-step swap (from Exercise 2) exchanges the elements at the two pointer positions without losing either value.
  • left++; right--: After each swap, both pointers move one step inward. The loop stops when they meet or cross, at which point every outer pair has been swapped and the array is reversed.

Exercise 28: Bubble Sort

Practice Problem: Write a program that sorts an integer array in ascending order using the Bubble Sort algorithm and prints the sorted result.

Exercise Purpose: To understand how nested loops can be used to repeatedly compare adjacent elements and bubble the largest unsorted value to its correct position, one pass at a time.

Given Input: arr = {64, 34, 25, 12, 22, 11, 90}

Expected Output: 11 12 22 25 34 64 90

▼ Hint
  • Use two nested loops: the outer loop runs n - 1 passes, and the inner loop compares adjacent pairs up to the last unsorted position.
  • If arr[j] > arr[j + 1], swap them using a temp variable. After each full pass of the inner loop, the largest remaining unsorted element will have moved to its correct position at the end.
▼ Solution and Explanation:
public class Main {
    public static void main(String[] args) {
        int[] arr = {64, 34, 25, 12, 22, 11, 90};
        int   n   = arr.length;
        for (int i = 0; i < n - 1; i++) {
            for (int j = 0; j < n - 1 - i; j++) {
                if (arr[j] > arr[j + 1]) {
                    int temp    = arr[j];
                    arr[j]      = arr[j + 1];
                    arr[j + 1]  = temp;
                }
            }
        }
        for (int num : arr) {
            System.out.print(num + " ");
        }
    }
}Code language: Java (java)

Explanation:

  • for (int i = 0; i < n - 1; i++): The outer loop controls the number of passes. Each pass guarantees that at least one more element has settled into its final sorted position at the end of the array.
  • j < n - 1 - i: The inner loop shrinks with each pass of the outer loop. Since the last i elements are already sorted and in place, there is no need to compare them again.
  • if (arr[j] > arr[j + 1]): Compares each element with its immediate neighbour. If they are out of order, they are swapped – this is the “bubble” step that pushes larger values rightward on each pass.

Exercise 29: Find Duplicate Elements

Practice Problem: Write a program that scans an integer array and prints any elements that appear more than once.

Exercise Purpose: To practice using nested loops where the inner loop checks every subsequent element against a chosen element in the outer loop, a classic pattern for pairwise comparison.

Given Input: arr = {1, 3, 4, 2, 3, 5, 4, 6}

Expected Output:

Duplicate found: 3
Duplicate found: 4
▼ Hint
  • Use two nested loops: the outer loop picks each element at index i, and the inner loop starts from i + 1 to compare it against every element that comes after it.
  • If arr[i] == arr[j], a duplicate has been found – print it, then break out of the inner loop to avoid printing the same duplicate more than once.
▼ Solution and Explanation:
public class Main {
    public static void main(String[] args) {
        int[] arr = {1, 3, 4, 2, 3, 5, 4, 6};
        System.out.println("Duplicates found:");
        for (int i = 0; i < arr.length - 1; i++) {
            for (int j = i + 1; j < arr.length; j++) {
                if (arr[i] == arr[j]) {
                    System.out.println("Duplicate found: " + arr[i]);
                    break;
                }
            }
        }
    }
}Code language: Java (java)

Explanation:

  • for (int i = 0; i < arr.length - 1; i++): The outer loop visits every element except the last one, since a duplicate must have a matching partner somewhere later in the array.
  • for (int j = i + 1; j < arr.length; j++): The inner loop starts just after the current outer index. This avoids comparing an element with itself and avoids checking pairs that have already been examined.
  • if (arr[i] == arr[j]): A match means the value at position i appears at least once more later in the array – it is a duplicate.
  • break: Exits the inner loop as soon as the first match for arr[i] is found, preventing the same value from being reported multiple times if it appears three or more times in the array.

Exercise 30: Merge Two Arrays

Practice Problem: Write a program that merges two separate integer arrays into a single new array and prints all the elements.

Exercise Purpose: To practice creating an array of a calculated size, copying elements from multiple source arrays using index arithmetic, and understanding how array positions map across boundaries.

Given Input: arr1 = {1, 2, 3}, arr2 = {4, 5, 6}

Expected Output: 1 2 3 4 5 6

▼ Hint
  • Create a new array whose length is arr1.length + arr2.length, then fill it in two separate loops.
  • For the second loop, write the elements of arr2 into the merged array starting at index arr1.length – that is where the first array ends and the second begins.
▼ Solution and Explanation:
public class Main {
    public static void main(String[] args) {
        int[] arr1   = {1, 2, 3};
        int[] arr2   = {4, 5, 6};
        int[] merged = new int[arr1.length + arr2.length];
        for (int i = 0; i < arr1.length; i++) {
            merged[i] = arr1[i];
        }
        for (int i = 0; i < arr2.length; i++) {
            merged[arr1.length + i] = arr2[i];
        }
        for (int num : merged) {
            System.out.print(num + " ");
        }
    }
}Code language: Java (java)

Explanation:

  • new int[arr1.length + arr2.length]: Allocates a new array large enough to hold every element from both source arrays, with no wasted space and no risk of running short.
  • merged[i] = arr1[i]: The first loop copies all elements from arr1 into the beginning of the merged array, occupying positions 0 through arr1.length - 1.
  • merged[arr1.length + i] = arr2[i]: The second loop places each element of arr2 immediately after the last element of arr1 by offsetting the destination index by arr1.length.

Exercise 31: Matrix Addition

Practice Problem: Write a program that declares two 3×3 integer matrices, adds them together element by element, and prints the resulting matrix.

Exercise Purpose: To learn how to declare and work with 2D arrays in Java, and to use nested loops to visit every row and column position in a grid-like structure.

Given Input:

A = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}}
B = {{9, 8, 7}, {6, 5, 4}, {3, 2, 1}}

Expected Output:

10 10 10
10 10 10
10 10 10
▼ Hint
  • Declare a 2D array with int[][] A = {{...}, {...}, {...}};. A second pair of square brackets signals the second dimension.
  • Use two nested for loops – the outer one iterates over rows and the inner one over columns. The sum at each position is A[i][j] + B[i][j], stored in a matching result array C[i][j].
▼ Solution and Explanation:
public class Main {
    public static void main(String[] args) {
        int[][] A = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
        int[][] B = {{9, 8, 7}, {6, 5, 4}, {3, 2, 1}};
        int[][] C = new int[3][3];
        for (int i = 0; i < 3; i++) {
            for (int j = 0; j < 3; j++) {
                C[i][j] = A[i][j] + B[i][j];
            }
        }
        System.out.println("Result:");
        for (int i = 0; i < 3; i++) {
            for (int j = 0; j < 3; j++) {
                System.out.print(C[i][j] + " ");
            }
            System.out.println();
        }
    }
}Code language: Java (java)

Explanation:

  • int[][] C = new int[3][3]: Declares an empty 3×3 result matrix. Java automatically fills it with zeros until values are assigned, so no manual initialisation is needed.
  • C[i][j] = A[i][j] + B[i][j]: The two indices i and j act as the row and column coordinates respectively. Adding the values at the same coordinates in both matrices and storing them in the result matrix is exactly what matrix addition means mathematically.
  • System.out.println() after the inner loop: Moves the cursor to the next line after each row is printed, so the output displays as a grid rather than a flat sequence of numbers.

Exercise 32: String Length (Manual Count)

Practice Problem: Write a program that finds the length of a string by iterating through its characters manually, without using the built-in length() method.

Exercise Purpose: To understand how strings are made up of individual characters that can be accessed one at a time, and to appreciate what the built-in length() method does under the hood.

Given Input: str = "Hello, World!"

Expected Output: Length = 13

▼ Hint
  • Convert the string to a character array using str.toCharArray(), then use a for-each loop to count each character.
  • Declare an integer counter starting at 0 before the loop and increment it by 1 on every iteration.
▼ Solution and Explanation:
public class Main {
    public static void main(String[] args) {
        String str   = "Hello, World!";
        int    count = 0;

        for (char c : str.toCharArray()) {
            count++;
        }

        System.out.println("Length = " + count);
    }
}Code language: Java (java)

Explanation:

  • str.toCharArray(): Converts the string into an array of char values, with one entry per character including spaces and punctuation, making it possible to loop through each one individually.
  • for (char c : str.toCharArray()): The for-each loop visits every character in order. The variable c holds the current character, though in this exercise its value is not used – only the fact that we visited it matters.
  • count++: Increments the counter by 1 for each character visited. After all characters have been processed, count holds the total length of the string.

Exercise 33: Palindrome String Checker

Practice Problem: Write a program that checks whether a given string reads the same forwards and backwards (i.e., is a palindrome), ignoring case.

Exercise Purpose: To practice combining string methods such as toLowerCase(), charAt(), and length() with a two-pointer loop to compare characters from opposite ends of a string.

Given Input: str = "Racecar"

Expected Output: "Racecar" is a Palindrome

▼ Hint
  • Convert the string to lowercase first with str.toLowerCase() so that the check is case-insensitive.
  • Use two index variables – one starting at the left and one at the right – and compare the characters at those positions using charAt(). If any pair does not match, it is not a palindrome.
▼ Solution and Explanation:
public class Main {
    public static void main(String[] args) {
        String str      = "Racecar";
        String lower    = str.toLowerCase();
        boolean isPalin = true;
        int left  = 0;
        int right = lower.length() - 1;
        while (left < right) {
            if (lower.charAt(left) != lower.charAt(right)) {
                isPalin = false;
                break;
            }
            left++;
            right--;
        }
        if (isPalin) {
            System.out.println("\"" + str + "\" is a Palindrome");
        } else {
            System.out.println("\"" + str + "\" is not a Palindrome");
        }
    }
}Code language: Java (java)

Explanation:

  • str.toLowerCase(): Creates a new lowercase copy of the string for comparison purposes. The original str is preserved so it can be printed with its original casing in the output message.
  • lower.charAt(left) != lower.charAt(right): Compares the characters at the outermost unvisited positions. If they differ at any point, the string cannot be a palindrome and the loop exits early.
  • left++; right--: Moves both pointers one step inward after a successful match, exactly as in the Reverse Array exercise. The loop ends when the pointers meet, meaning every symmetric pair has been verified.

Exercise 34: Uppercase & Lowercase Conversion

Practice Problem: Write a program that takes a mixed-case string and prints both its fully uppercase and fully lowercase versions.

Exercise Purpose: To get familiar with Java’s built-in String methods and to understand that strings in Java are immutable – methods like toUpperCase() return a new string rather than modifying the original.

Given Input: str = "Hello, World!"

Expected Output:

Uppercase: HELLO, WORLD!
Lowercase: hello, world!
▼ Hint
  • Use str.toUpperCase() to get the uppercase version and str.toLowerCase() for the lowercase version.
  • Both methods return a brand new String object – they do not change str itself. Store each result in a separate variable or print them directly.
▼ Solution and Explanation:
public class Main {
    public static void main(String[] args) {
        String str       = "Hello, World!";
        String uppercase = str.toUpperCase();
        String lowercase = str.toLowerCase();

        System.out.println("Uppercase: " + uppercase);
        System.out.println("Lowercase: " + lowercase);
    }
}Code language: Java (java)

Explanation:

  • str.toUpperCase(): Returns a new string where every lowercase letter has been converted to its uppercase equivalent. Non-letter characters such as spaces, commas, and exclamation marks are left unchanged.
  • str.toLowerCase(): Returns another new string where every uppercase letter is converted to lowercase. Again, non-letter characters are unaffected.
  • Immutability of strings: After calling both methods, the original variable str still holds "Hello, World!" unchanged. In Java, String objects can never be modified in place – every method that appears to change a string actually returns a new one.

Exercise 35: Remove Spaces from String

Practice Problem: Write a program that removes all whitespace characters from a given string and prints the result.

Exercise Purpose: To practice iterating through a string character by character and selectively building a new string, which introduces the StringBuilder class as an efficient way to construct strings inside a loop.

Given Input: str = "Hello, World! How are you?"

Expected Output: Hello,World!Howareyou?

▼ Hint
  • Loop through each character of the string using toCharArray() and only append the character to your result if it is not a space: if (c != ' ').
  • Use a StringBuilder to build the result. Repeatedly concatenating strings with + inside a loop creates many temporary objects and is inefficient – StringBuilder.append() is the correct approach.
▼ Solution and Explanation:
public class Main {
    public static void main(String[] args) {
        String        str    = "Hello, World! How are you?";
        StringBuilder result = new StringBuilder();

        for (char c : str.toCharArray()) {
            if (c != ' ') {
                result.append(c);
            }
        }

        System.out.println(result.toString());
    }
}Code language: Java (java)

Explanation:

  • StringBuilder result = new StringBuilder(): Creates a mutable sequence of characters. Unlike a regular String, a StringBuilder can be modified in place, making it the right tool for building a string incrementally inside a loop.
  • if (c != ' '): The condition filters out space characters. Every other character, including punctuation and letters, passes through and is added to the result.
  • result.append(c): Adds the current character to the end of the StringBuilder buffer without creating a new object each time, which is far more efficient than string concatenation with + in a loop.
  • result.toString(): Converts the finished StringBuilder back into a regular String for printing.

Exercise 36: Character Frequency Counter

Practice Problem: Write a program that counts how many times each character appears in a given string and prints each character alongside its frequency.

Exercise Purpose: To practice using an integer array indexed by character values as a simple frequency table, and to see how characters and integers relate to each other through their ASCII codes.

Given Input: str = "hello"

Expected Output:

h: 1
e: 1
l: 2
o: 1
▼ Hint
  • Create an integer array of size 256 (one slot for each possible ASCII character) and use each character as an index: freq[c]++.
  • After counting, loop through the original string again and print only the characters whose frequency is greater than zero, to avoid printing empty slots.
▼ Solution and Explanation:
public class Main {
    public static void main(String[] args) {
        String str  = "hello";
        int[]  freq = new int[256];

        for (char c : str.toCharArray()) {
            freq[c]++;
        }

        for (char c : str.toCharArray()) {
            if (freq[c] > 0) {
                System.out.println(c + ": " + freq[c]);
                freq[c] = 0; // mark as printed
            }
        }
    }
}Code language: Java (java)

Explanation:

  • int[] freq = new int[256]: Creates a frequency table with 256 slots, one for each standard ASCII character. Java initialises all slots to zero automatically.
  • freq[c]++: In Java, a char can be used directly as an integer index because each character has a numeric ASCII code. For example, 'h' has the code 104, so freq[104] is incremented when 'h' is encountered.
  • if (freq[c] > 0): Only prints characters that were actually found in the string. After printing, the slot is reset to 0 so that characters appearing more than once (like 'l') are not printed a second time on the next encounter.

Exercise 37: String Anagrams

Practice Problem: Write a Java program to check whether two given strings are anagrams of each other.

Purpose: This exercise helps you practice sorting character arrays and comparing data, a common technique used in string comparison and puzzle-solving problems.

Given Input: str1 = "listen", str2 = "silent"

Expected Output: "listen" and "silent" are anagrams

▼ Hint
  • Convert both strings to lowercase.
  • Convert each string to a character array using toCharArray().
  • Sort both character arrays using Arrays.sort().
  • Compare the sorted arrays using Arrays.equals().
▼ Solution & Explanation

Solution:

import java.util.Arrays;

public class Main {
    public static void main(String[] args) {
        String str1 = "listen";
        String str2 = "silent";

        char[] arr1 = str1.toLowerCase().toCharArray();
        char[] arr2 = str2.toLowerCase().toCharArray();

        Arrays.sort(arr1);
        Arrays.sort(arr2);

        if (Arrays.equals(arr1, arr2)) {
            System.out.println("\"" + str1 + "\" and \"" + str2 + "\" are anagrams");
        } else {
            System.out.println("\"" + str1 + "\" and \"" + str2 + "\" are not anagrams");
        }
    }
}Code language: Java (java)

Explanation:

  • toCharArray(): Converts each string into an array of individual characters for comparison.
  • Arrays.sort(arr1): Sorts the characters alphabetically so both arrays can be compared position by position.
  • Arrays.equals(arr1, arr2): Returns true only if both arrays have the same characters in the same order after sorting.

Exercise 38: Custom Method: isEven

Practice Problem: Write a program with a reusable static method named isEven that takes an integer and returns true if it is even and false if it is odd. Call the method from main with a few test values.

Exercise Purpose: To learn how to define and call your own static methods in Java, understand method signatures (return type and parameters), and see how returning a value from a method is different from printing directly inside it.

Given Input: Test values 4 and 7

Expected Output:

4 is even: true
7 is even: false
▼ Hint
  • Define the method outside main but inside the class with the signature public static boolean isEven(int number).
  • Inside the method, use return number % 2 == 0; – this single line evaluates the condition and returns the resulting boolean directly.
▼ Solution and Explanation:
public class Main {

    public static boolean isEven(int number) {
        return number % 2 == 0;
    }

    public static void main(String[] args) {
        int a = 4;
        int b = 7;

        System.out.println(a + " is even: " + isEven(a));
        System.out.println(b + " is even: " + isEven(b));
    }
}Code language: Java (java)

Explanation:

  • public static boolean isEven(int number): The method signature declares that this method is accessible from anywhere (public), belongs to the class rather than an instance (static), returns a boolean value, and accepts one integer parameter named number.
  • return number % 2 == 0: The expression number % 2 == 0 evaluates to either true or false, and that boolean is returned directly to wherever the method was called from – no intermediate variable needed.
  • isEven(a) inside println: The method call is used directly inside the print statement. Java evaluates isEven(a) first, gets back a boolean, and then concatenates it into the output string.

Exercise 39: Class and Object Basics

Practice Problem: Create a Student class with fields for name and rollNumber, and a displayInfo() method that prints those details. In a separate main method, create a Student object, assign values to its fields, and call the method.

Exercise Purpose: To understand the fundamental building block of object-oriented programming in Java – defining a class as a blueprint and creating an object (instance) from it, then accessing its fields and methods.

Given Input: name = "Alice", rollNumber = 101

Expected Output:

Student Name:        Alice
Student Roll Number: 101
▼ Hint
  • Define the Student class with two fields (String name and int rollNumber) and a non-static method displayInfo() that prints them.
  • In main, create an instance with Student s = new Student();, assign values using dot notation (s.name = "Alice"), then call s.displayInfo().
▼ Solution and Explanation:
class Student {
    String name;
    int    rollNumber;

    void displayInfo() {
        System.out.println("Student Name:        " + name);
        System.out.println("Student Roll Number: " + rollNumber);
    }
}

public class Main {
    public static void main(String[] args) {
        Student s    = new Student();
        s.name       = "Alice";
        s.rollNumber = 101;

        s.displayInfo();
    }
}Code language: Java (java)

Explanation:

  • class Student: Defines a blueprint that describes what data a student holds (name, rollNumber) and what it can do (displayInfo()). No memory is allocated yet at this point – the class is just a template.
  • Student s = new Student(): The new keyword allocates memory for a real object based on the Student blueprint and returns a reference to it, stored in the variable s.
  • s.name = "Alice": Dot notation accesses the field named name on the specific object referred to by s, and assigns a value to it.
  • s.displayInfo(): Calls the method on the object s. Inside the method, name and rollNumber automatically refer to the values belonging to s, not to any other student object.

Exercise 40: Constructors in Java

Practice Problem: Create a Book class with a constructor that accepts a title and an author, stores them as fields, and provides a displayInfo() method. Create two Book objects in main using the constructor and print their details.

Exercise Purpose: To learn how constructors work as a cleaner, more reliable way to initialise an object’s fields at the moment it is created, instead of assigning values separately after creation.

Given Input: Book 1 – title = "1984", author = "George Orwell". Book 2 – title = "Dune", author = "Frank Herbert".

Expected Output:

Title: 1984  |  Author: George Orwell
Title: Dune  |  Author: Frank Herbert
▼ Hint
  • A constructor has the same name as the class and no return type. Define it as Book(String title, String author) and use this.title = title inside it to assign the parameter values to the fields.
  • Create objects by passing arguments directly to new: Book b1 = new Book("1984", "George Orwell");.
▼ Solution and Explanation:
class Book {
    String title;
    String author;

    Book(String title, String author) {
        this.title  = title;
        this.author = author;
    }

    void displayInfo() {
        System.out.println("Title: " + title + "  |  Author: " + author);
    }
}

public class Main {
    public static void main(String[] args) {
        Book b1 = new Book("1984", "George Orwell");
        Book b2 = new Book("Dune", "Frank Herbert");

        b1.displayInfo();
        b2.displayInfo();
    }
}Code language: Java (java)

Explanation:

  • Book(String title, String author): This is the constructor. It is called automatically by Java the moment new Book(...) is executed, allowing the object to be fully initialised in a single step.
  • this.title = title: The keyword this refers to the current object being constructed. It is used here to distinguish between the field named title (belonging to the object) and the parameter also named title (local to the constructor).
  • new Book("1984", "George Orwell"): The arguments passed to new are forwarded directly into the constructor parameters, so the object arrives fully initialised – no separate assignment steps needed.

Exercise 41: Method Overloading

Practice Problem: Write a class with two overloaded versions of a method named calculateArea: one that takes a single integer (side of a square) and one that takes two integers (length and width of a rectangle). Call both from main and print the results.

Exercise Purpose: To understand method overloading – the ability to define multiple methods with the same name but different parameter lists – and to see how Java automatically selects the correct version based on the arguments provided at the call site.

Given Input: Square with side = 5. Rectangle with length = 8, width = 3.

Expected Output:

Area of square    = 25
Area of rectangle = 24
▼ Hint
  • Define both methods with the name calculateArea in the same class. Java differentiates them by the number of parameters: calculateArea(int side) for a square, calculateArea(int length, int width) for a rectangle.
  • When you call calculateArea(5), Java picks the one-parameter version automatically. When you call calculateArea(8, 3), it picks the two-parameter version.
▼ Solution and Explanation:
public class Main {

    // Area of a square
    public static int calculateArea(int side) {
        return side * side;
    }

    // Area of a rectangle
    public static int calculateArea(int length, int width) {
        return length * width;
    }

    public static void main(String[] args) {
        System.out.println("Area of square    = " + calculateArea(5));
        System.out.println("Area of rectangle = " + calculateArea(8, 3));
    }
}Code language: Java (java)

Explanation:

  • Two methods named calculateArea: Java allows this because their parameter lists are different – one takes a single int, the other takes two. The combination of method name and parameter list is called the method’s signature, and each overload must have a unique signature.
  • calculateArea(5): Java sees one argument and matches it to the single-parameter version, computing 5 * 5 = 25.
  • calculateArea(8, 3): Java sees two arguments and selects the two-parameter version, computing 8 * 3 = 24. This selection happens at compile time, not at runtime.

Exercise 42: Encapsulation with BankAccount

Practice Problem: Create a BankAccount class with a private balance field and public methods for getting the balance, setting an initial balance, depositing money, and withdrawing money. Demonstrate all four methods from main.

Exercise Purpose: To understand encapsulation – hiding an object’s internal data behind a private access modifier and exposing controlled access through public methods, so that the data can never be put into an invalid state from outside the class.

Given Input: Initial balance 1000, deposit 500, withdraw 200.

Expected Output:

Initial balance: 1000
After deposit:   1500
After withdraw:  1300
Current balance: 1300
▼ Hint
  • Declare the field as private double balance;. Then write a getBalance() method that returns it and a setBalance(double amount) method that assigns it.
  • In deposit(), add the amount to the balance. In withdraw(), subtract it – but first check that the requested amount does not exceed the available balance and print an error message if it does.
▼ Solution and Explanation:
class BankAccount {
    private double balance;
    // Setter
    public void setBalance(double amount) {
        if (amount >= 0) {
            balance = amount;
        }
    }
    // Getter
    public double getBalance() {
        return balance;
    }
    // Deposit
    public void deposit(double amount) {
        if (amount > 0) {
            balance += amount;
            System.out.println("After deposit:   " + balance);
        }
    }
    // Withdraw
    public void withdraw(double amount) {
        if (amount > 0 && amount <= balance) {
            balance -= amount;
            System.out.println("After withdraw:  " + balance);
        } else {
            System.out.println("Insufficient funds.");
        }
    }
}
public class Main {
    public static void main(String[] args) {
        BankAccount account = new BankAccount();
        account.setBalance(1000);
        System.out.println("Initial balance: " + account.getBalance());
        account.deposit(500);
        account.withdraw(200);
        System.out.println("Current balance: " + account.getBalance());
    }
}Code language: Java (java)

Explanation:

  • private double balance: The private keyword means no code outside the BankAccount class can read or write this field directly. Any attempt to write account.balance = -500 from main would cause a compile error.
  • getBalance() and setBalance(): These are the getter and setter methods – the controlled gates through which outside code can read and write the balance. The setter includes a guard (amount >= 0) that prevents the balance from being set to a negative value, something that would be impossible to enforce if the field were public.
  • withdraw(double amount): The guard condition amount <= balance ensures a withdrawal can never push the balance below zero. This business rule lives inside the class where it belongs – the caller in main does not need to remember to check it.
  • Encapsulation in practice: By making balance private and routing all changes through methods, the class guarantees its own data stays valid no matter how it is used from outside. This is the core promise of encapsulation.

Exercise 43: Demonstrate Inheritance with an Animal and Dog Class

Practice Problem: Write a Java program that creates an Animal class and a Dog class that inherits from it, demonstrating basic inheritance.

Purpose: This exercise helps you practice defining a parent-child class relationship using the extends keyword, one of the four core pillars of object-oriented programming.

Given Input: Create a Dog object and call its inherited and own methods.

Expected Output:

This animal eats food.
The dog barks.
▼ Hint
  • Create a class Animal with a method like eat().
  • Create a class Dog that extends Animal and adds its own method like bark().
  • Create a Dog object in main and call both eat() (inherited) and bark() (own method).
  • Notice that Dog automatically gains access to Animal’s methods without redefining them.
▼ Solution & Explanation

Solution:

class Animal {
    void eat() {
        System.out.println("This animal eats food.");
    }
}

class Dog extends Animal {
    void bark() {
        System.out.println("The dog barks.");
    }
}

public class Main {
    public static void main(String[] args) {
        Dog dog = new Dog();
        dog.eat();
        dog.bark();
    }
}Code language: Java (java)

Explanation:

  • class Dog extends Animal: Establishes an inheritance relationship, making Dog a subclass that automatically inherits all accessible members of Animal.
  • dog.eat(): Calls the inherited method from the Animal class, even though Dog never defines it directly.
  • dog.bark(): Calls the method defined directly in the Dog subclass.

Exercise 44: Demonstrate Method Overriding (Runtime Polymorphism)

Practice Problem: Write a Java program that demonstrates method overriding by having a subclass provide its own implementation of a parent class method.

Purpose: This exercise helps you practice overriding methods with the @Override annotation, which enables runtime polymorphism, one of Java’s key object-oriented features.

Given Input: Create a Shape reference pointing to a Circle object and call its draw() method.

Expected Output: Drawing a circle.

▼ Hint
  • Create a class Shape with a method draw() that prints a generic message.
  • Create a class Circle that extends Shape and overrides draw() using @Override.
  • Declare a Shape reference variable, but assign it a new Circle() object.
  • Call draw() through the Shape reference and observe that the Circle version runs.
▼ Solution & Explanation

Solution:

class Shape {
    void draw() {
        System.out.println("Drawing a shape.");
    }
}

class Circle extends Shape {
    @Override
    void draw() {
        System.out.println("Drawing a circle.");
    }
}

public class Main {
    public static void main(String[] args) {
        Shape shape = new Circle();
        shape.draw();
    }
}Code language: Java (java)

Explanation:

  • @Override: Indicates that the method in Circle is intentionally replacing the version defined in Shape, and helps the compiler catch mistakes.
  • Shape shape = new Circle(): Declares a reference of type Shape but points it to a Circle object, a valid use of polymorphism.
  • shape.draw(): Even though the reference type is Shape, Java calls the overridden version in Circle at runtime, based on the actual object type.

Exercise 45: Demonstrate Static Variables and Static Methods

Practice Problem: Write a Java program that demonstrates static variables and static methods by tracking how many objects of a class have been created.

Purpose: This exercise helps you practice using the static keyword, which allows a variable or method to belong to the class itself rather than to any individual object, useful for tracking shared state like counters.

Given Input: Create three Counter objects.

Expected Output: Total Counters Created = 3

▼ Hint
  • Declare a static variable like count in the Counter class, initialized to 0.
  • Increment count inside the constructor every time a new object is created.
  • Declare a static method like getCount() that returns the current value of count.
  • Create multiple objects, then call the static method once to print the total.
▼ Solution & Explanation

Solution:

class Counter {
    static int count = 0;

    Counter() {
        count++;
    }

    static int getCount() {
        return count;
    }
}

public class Main {
    public static void main(String[] args) {
        Counter c1 = new Counter();
        Counter c2 = new Counter();
        Counter c3 = new Counter();

        System.out.println("Total Counters Created = " + Counter.getCount());
    }
}Code language: Java (java)

Explanation:

  • static int count = 0: Declares a variable shared by all instances of Counter rather than a separate copy for each object.
  • count++ inside the constructor: Increments the shared counter every time a new Counter object is created.
  • static int getCount(): A static method that can be called on the class itself (Counter.getCount()) without needing an object instance.

Exercise 46: Create and Print an ArrayList of Integers

Practice Problem: Write a Java program to create an ArrayList of integers, add elements to it, and print the entire list.

Purpose: This exercise helps you practice creating and populating an ArrayList, Java’s most commonly used resizable list implementation, and understand how it differs from arrays.

Given Input: Add the numbers 10, 20, 30, 40, 50

Expected Output: [10, 20, 30, 40, 50]

▼ Hint

Create an ArrayList<Integer> and use the add() method to insert elements, then pass the list directly to System.out.println() to display it.

▼ Solution & Explanation

Solution:

import java.util.ArrayList;

public class Main {
    public static void main(String[] args) {
        ArrayList<Integer> numbers = new ArrayList<>();
        numbers.add(10);
        numbers.add(20);
        numbers.add(30);
        numbers.add(40);
        numbers.add(50);

        System.out.println(numbers);
    }
}Code language: Java (java)

Explanation:

  • new ArrayList<Integer>(): Creates an empty resizable list that can hold Integer values.
  • numbers.add(10): Appends an element to the end of the ArrayList.
  • System.out.println(numbers): Automatically calls the ArrayList’s built-in toString() method to print all elements in bracket notation.

Exercise 47: Add, Remove, and Search Elements in an ArrayList

Practice Problem: Write a Java program to add elements to an ArrayList, remove a specific element, and search for another element.

Purpose: This exercise helps you practice core ArrayList operations, add(), remove(), and contains(), which form the basis of everyday list manipulation in Java.

Given Input: fruits = ["Apple", "Banana", "Mango", "Orange"], remove "Banana", search for "Mango"

Expected Output:

After Removal: [Apple, Mango, Orange]
Contains Mango: true
▼ Hint
  • Create an ArrayList<String> and add all the fruit names.
  • Use remove() with the element value to delete "Banana".
  • Use contains() to check if "Mango" exists in the list.
  • Print the updated list and the search result.
▼ Solution & Explanation

Solution:

import java.util.ArrayList;

public class Main {
    public static void main(String[] args) {
        ArrayList<String> fruits = new ArrayList<>();
        fruits.add("Apple");
        fruits.add("Banana");
        fruits.add("Mango");
        fruits.add("Orange");

        fruits.remove("Banana");
        boolean hasMango = fruits.contains("Mango");

        System.out.println("After Removal: " + fruits);
        System.out.println("Contains Mango: " + hasMango);
    }
}Code language: Java (java)

Explanation:

  • fruits.remove("Banana"): Removes the first occurrence of the specified element from the list.
  • fruits.contains("Mango"): Returns true if the list contains the given element, false otherwise.
  • "After Removal: " + fruits: Concatenates the string label with the ArrayList’s printable representation.

Exercise 48: Sort an ArrayList of Strings Alphabetically

Practice Problem: Write a Java program to sort an ArrayList of strings in alphabetical order.

Purpose: This exercise helps you practice using the Collections.sort() method to arrange list elements, a frequently used utility for organizing data before display or processing.

Given Input: names = ["Charlie", "Alice", "Bob", "David"]

Expected Output: [Alice, Bob, Charlie, David]

▼ Hint

Use Collections.sort() and pass the ArrayList to it; it sorts String elements in natural (alphabetical) order by default.

▼ Solution & Explanation

Solution:

import java.util.ArrayList;
import java.util.Collections;

public class Main {
    public static void main(String[] args) {
        ArrayList<String> names = new ArrayList<>();
        names.add("Charlie");
        names.add("Alice");
        names.add("Bob");
        names.add("David");

        Collections.sort(names);

        System.out.println(names);
    }
}Code language: Java (java)

Explanation:

  • Collections.sort(names): Sorts the ArrayList in place using the natural ordering of its elements, which for String means alphabetical order.
  • System.out.println(names): Prints the sorted list using its default bracket-notation format.

Exercise 49: Create a HashMap and Iterate Over Its Key-Value Pairs

Practice Problem: Write a Java program to create a HashMap of student names and their marks, then iterate over it to print each key-value pair.

Purpose: This exercise helps you practice creating a HashMap, adding key-value pairs, and iterating over its entrySet(), a common pattern for working with associative data in Java.

Given Input: {"Alice": 85, "Bob": 92, "Charlie": 78}

Expected Output: (order may vary since HashMap does not guarantee insertion order)

Alice = 85
Bob = 92
Charlie = 78
▼ Hint
  • Create a HashMap<String, Integer> to store names as keys and marks as values.
  • Use put() to add each key-value pair.
  • Use entrySet() with a for-each loop to iterate over the map.
  • Access each entry’s key and value using getKey() and getValue().
▼ Solution & Explanation

Solution:

import java.util.HashMap;
import java.util.Map;

public class Main {
    public static void main(String[] args) {
        HashMap<String, Integer> marks = new HashMap<>();
        marks.put("Alice", 85);
        marks.put("Bob", 92);
        marks.put("Charlie", 78);

        for (Map.Entry<String, Integer> entry : marks.entrySet()) {
            System.out.println(entry.getKey() + " = " + entry.getValue());
        }
    }
}Code language: Java (java)

Explanation:

  • marks.put("Alice", 85): Inserts a key-value pair into the HashMap, using the student name as the key and the mark as the value.
  • marks.entrySet(): Returns a set view of all key-value pairs stored in the map.
  • entry.getKey() / entry.getValue(): Retrieves the key and value from each Map.Entry object during iteration.
  • Note: HashMap does not guarantee any specific order, so the printed order of entries may differ from the insertion order.

Exercise 50: Count Word Frequency in a Sentence Using HashMap

Practice Problem: Write a Java program to count how many times each word appears in a given sentence using a HashMap.

Purpose: This exercise helps you practice combining string splitting with HashMap operations like getOrDefault(), a widely used pattern for frequency counting and text analysis.

Given Input: sentence = "the quick brown fox jumps over the lazy dog the fox runs"

Expected Output: (order may vary since HashMap does not guarantee insertion order)

the = 3
quick = 1
brown = 1
fox = 2
jumps = 1
over = 1
lazy = 1
dog = 1
runs = 1
▼ Hint
  • Split the sentence into words using split(" ").
  • Loop through each word and use getOrDefault() to retrieve its current count, defaulting to 0.
  • Use put() to update the count for that word by adding 1.
  • Iterate over the map using entrySet() to print the final word frequencies.
▼ Solution & Explanation

Solution:

import java.util.HashMap;
import java.util.Map;

public class Main {
    public static void main(String[] args) {
        String sentence = "the quick brown fox jumps over the lazy dog the fox runs";
        String[] words = sentence.split(" ");

        HashMap<String, Integer> wordCount = new HashMap<>();

        for (String word : words) {
            wordCount.put(word, wordCount.getOrDefault(word, 0) + 1);
        }

        for (Map.Entry<String, Integer> entry : wordCount.entrySet()) {
            System.out.println(entry.getKey() + " = " + entry.getValue());
        }
    }
}Code language: Java (java)

Explanation:

  • sentence.split(" "): Splits the sentence into an array of individual words using a space as the delimiter.
  • wordCount.getOrDefault(word, 0): Returns the current count for the word, or 0 if the word has not been seen before, avoiding a null pointer exception.
  • wordCount.put(word, ... + 1): Updates the map with the incremented count for that word.
  • Note: HashMap does not guarantee insertion order, so the output order of words may vary.

Exercise 51: Remove Duplicate Elements from an ArrayList

Practice Problem: Write a Java program to remove duplicate elements from an ArrayList of integers while preserving the order of first occurrence.

Purpose: This exercise helps you practice combining ArrayList and LinkedHashSet to eliminate duplicates without manually tracking seen elements, a common data-cleaning task.

Given Input: numbers = [10, 20, 10, 30, 20, 40]

Expected Output: [10, 20, 30, 40]

▼ Hint
  • Create a LinkedHashSet<Integer> from the ArrayList to remove duplicates while preserving insertion order.
  • Clear the original ArrayList.
  • Add all elements back from the LinkedHashSet into the ArrayList.
  • Print the resulting list.
▼ Solution & Explanation

Solution:

import java.util.ArrayList;
import java.util.LinkedHashSet;

public class Main {
    public static void main(String[] args) {
        ArrayList<Integer> numbers = new ArrayList<>();
        numbers.add(10);
        numbers.add(20);
        numbers.add(10);
        numbers.add(30);
        numbers.add(20);
        numbers.add(40);

        LinkedHashSet<Integer> uniqueSet = new LinkedHashSet<>(numbers);
        numbers.clear();
        numbers.addAll(uniqueSet);

        System.out.println(numbers);
    }
}Code language: Java (java)

Explanation:

  • new LinkedHashSet<Integer>(numbers): Creates a LinkedHashSet from the ArrayList, which automatically removes duplicates while preserving the order elements first appeared in.
  • numbers.clear(): Empties the original ArrayList so it can be repopulated with unique values.
  • numbers.addAll(uniqueSet): Copies all unique elements from the LinkedHashSet back into the ArrayList.

Exercise 52: Sort a HashMap by Its Values

Practice Problem: Write a Java program to sort a HashMap of names and scores in ascending order of their values.

Purpose: This exercise helps you practice converting a HashMap’s entries into a sortable list and using a comparator, a common requirement when ranking or displaying data by value rather than by key.

Given Input: {"Alice": 85, "Bob": 60, "Charlie": 92, "David": 75}

Expected Output:

Bob = 60
David = 75
Alice = 85
Charlie = 92
▼ Hint
  • Convert the HashMap’s entrySet() into a List<Map.Entry<String, Integer>>.
  • Sort the list using Map.Entry.comparingByValue().
  • Iterate through the sorted list and print each entry.
  • Remember that the original HashMap itself is not sorted, only the extracted list is.
▼ Solution & Explanation

Solution:

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class Main {
    public static void main(String[] args) {
        HashMap<String, Integer> scores = new HashMap<>();
        scores.put("Alice", 85);
        scores.put("Bob", 60);
        scores.put("Charlie", 92);
        scores.put("David", 75);

        List<Map.Entry<String, Integer>> entryList = new ArrayList<>(scores.entrySet());
        entryList.sort(Map.Entry.comparingByValue());

        for (Map.Entry<String, Integer> entry : entryList) {
            System.out.println(entry.getKey() + " = " + entry.getValue());
        }
    }
}Code language: Java (java)

Explanation:

  • new ArrayList<>(scores.entrySet()): Copies the HashMap’s entries into a List so they can be sorted, since HashMap itself has no defined order.
  • entryList.sort(Map.Entry.comparingByValue()): Sorts the list of entries in ascending order based on their values using a built-in comparator.
  • entry.getKey() / entry.getValue(): Reads the name and score from each sorted entry for printing.

Exercise 53: Create a TreeMap and Print Keys in Sorted Order

Practice Problem: Write a Java program to create a TreeMap of product names and prices, then print its entries in sorted key order.

Purpose: This exercise helps you practice using TreeMap, which automatically keeps its keys sorted in natural order, a useful alternative to HashMap when ordering matters.

Given Input: {"Banana": 40, "Apple": 120, "Mango": 90, "Cherry": 200}

Expected Output:

Apple = 120
Banana = 40
Cherry = 200
Mango = 90
▼ Hint
  • Create a TreeMap<String, Integer> and add the key-value pairs using put().
  • Unlike HashMap, TreeMap automatically sorts keys in natural (alphabetical) order.
  • Use entrySet() with a for-each loop to iterate over the sorted entries.
  • Print each key-value pair.
▼ Solution & Explanation

Solution:

import java.util.Map;
import java.util.TreeMap;

public class Main {
    public static void main(String[] args) {
        TreeMap<String, Integer> products = new TreeMap<>();
        products.put("Banana", 40);
        products.put("Apple", 120);
        products.put("Mango", 90);
        products.put("Cherry", 200);

        for (Map.Entry<String, Integer> entry : products.entrySet()) {
            System.out.println(entry.getKey() + " = " + entry.getValue());
        }
    }
}Code language: Java (java)

Explanation:

  • new TreeMap<String, Integer>(): Creates a map that automatically sorts its keys in natural ascending order as elements are added.
  • products.put("Banana", 40): Inserts each key-value pair; TreeMap places it in the correct sorted position internally.
  • products.entrySet(): Returns entries already sorted by key, so no extra sorting step is needed before printing.

Exercise 54: Check if a Key Exists in a HashMap Using containsKey()

Practice Problem: Write a Java program to check whether a specific key exists in a HashMap of employee IDs and names.

Purpose: This exercise helps you practice using the containsKey() method to safely check for a key’s presence before accessing its value, avoiding unnecessary null checks.

Given Input: {101: "John", 102: "Sara", 103: "Mike"}, search key = 102

Expected Output: Key 102 exists with value Sara

▼ Hint

Use containsKey() to check whether the key is present in the map, then use get() to retrieve its value only if the key exists.

▼ Solution & Explanation

Solution:

import java.util.HashMap;

public class Main {
    public static void main(String[] args) {
        HashMap<Integer, String> employees = new HashMap<>();
        employees.put(101, "John");
        employees.put(102, "Sara");
        employees.put(103, "Mike");

        int searchKey = 102;

        if (employees.containsKey(searchKey)) {
            System.out.println("Key " + searchKey + " exists with value " + employees.get(searchKey));
        } else {
            System.out.println("Key " + searchKey + " does not exist");
        }
    }
}Code language: Java (java)

Explanation:

  • employees.containsKey(searchKey): Returns true if the given key is present in the map, without needing to check for a null value.
  • employees.get(searchKey): Retrieves the value associated with the key, called only after confirming the key exists.
  • if / else: Prints a different message depending on whether the key was found.

Exercise 55: Remove Duplicate Elements from an Array Using HashSet

Practice Problem: Write a Java program to remove duplicate elements from an integer array using a HashSet.

Purpose: This exercise helps you practice using HashSet’s automatic duplicate-elimination property, a fast and simple way to obtain unique values from a collection.

Given Input: numbers = [5, 3, 8, 3, 5, 9, 8]

Expected Output: [3, 5, 8, 9] (order may vary since HashSet does not guarantee order)

▼ Hint
  • Create a HashSet<Integer> and add each element of the array to it.
  • HashSet automatically discards duplicate values as they are added.
  • Print the resulting set directly to see the unique values.
  • Remember that HashSet does not preserve insertion order.
▼ Solution & Explanation

Solution:

import java.util.HashSet;

public class Main {
    public static void main(String[] args) {
        int[] numbers = {5, 3, 8, 3, 5, 9, 8};

        HashSet<Integer> uniqueNumbers = new HashSet<>();
        for (int num : numbers) {
            uniqueNumbers.add(num);
        }

        System.out.println(uniqueNumbers);
    }
}Code language: Java (java)

Explanation:

  • new HashSet<Integer>(): Creates an empty set that automatically rejects duplicate values.
  • uniqueNumbers.add(num): Adds each array element to the set; duplicate values are silently ignored.
  • Note: HashSet does not guarantee any particular order, so the printed order of elements may vary.

Exercise 56: Store and Print Unique Elements in Sorted Order Using TreeSet

Practice Problem: Write a Java program to store a group of numbers in a TreeSet and print the unique elements in sorted order.

Purpose: This exercise helps you practice using TreeSet, which combines the duplicate-removal behavior of a Set with automatic sorting, useful when you need unique and ordered data together.

Given Input: numbers = [45, 12, 78, 12, 3, 45, 56]

Expected Output: [3, 12, 45, 56, 78]

▼ Hint

Add all elements to a TreeSet; duplicates are automatically removed and the remaining elements are kept in ascending sorted order.

▼ Solution & Explanation

Solution:

import java.util.TreeSet;

public class Main {
    public static void main(String[] args) {
        int[] numbers = {45, 12, 78, 12, 3, 45, 56};

        TreeSet<Integer> uniqueSorted = new TreeSet<>();
        for (int num : numbers) {
            uniqueSorted.add(num);
        }

        System.out.println(uniqueSorted);
    }
}Code language: Java (java)

Explanation:

  • new TreeSet<Integer>(): Creates a set that keeps its elements sorted in ascending order and automatically removes duplicates.
  • uniqueSorted.add(num): Adds each number; duplicates are ignored and unique values are inserted in their correct sorted position.
  • System.out.println(uniqueSorted): Prints the elements already sorted, requiring no additional sorting step.

Exercise 57: Find Common Elements Between Two Sets Using HashSet

Practice Problem: Write a Java program to find the common elements between two integer arrays using HashSet and the retainAll() method.

Purpose: This exercise helps you practice using retainAll() to compute the intersection of two collections, a technique used in data comparison and filtering tasks.

Given Input: arr1 = [1, 2, 3, 4, 5], arr2 = [3, 4, 5, 6, 7]

Expected Output: [3, 4, 5] (order may vary since HashSet does not guarantee order)

▼ Hint
  • Create two HashSet<Integer> objects and populate each from its respective array.
  • Call retainAll() on the first set, passing the second set as the argument.
  • retainAll() keeps only the elements present in both sets, removing everything else.
  • Print the resulting set to see the common elements.
▼ Solution & Explanation

Solution:

import java.util.HashSet;

public class Main {
    public static void main(String[] args) {
        int[] arr1 = {1, 2, 3, 4, 5};
        int[] arr2 = {3, 4, 5, 6, 7};

        HashSet<Integer> set1 = new HashSet<>();
        for (int num : arr1) {
            set1.add(num);
        }

        HashSet<Integer> set2 = new HashSet<>();
        for (int num : arr2) {
            set2.add(num);
        }

        set1.retainAll(set2);

        System.out.println(set1);
    }
}Code language: Java (java)

Explanation:

  • set1.retainAll(set2): Modifies set1 so it retains only the elements that are also present in set2, effectively computing the intersection.
  • set1.add(num) / set2.add(num): Populates each set from its corresponding array, automatically discarding any duplicate values within the same array.
  • System.out.println(set1): Prints the common elements remaining in set1 after the intersection.

Exercise 58: Get and Print the Current Date and Time

Practice Problem: Write a Java program to get and print the current date and time using the LocalDate and LocalDateTime classes.

Purpose: This exercise helps you practice using the java.time API to retrieve the system’s current date and time, a fundamental skill for logging, timestamps, and time based features.

Given Input: None. The program reads the current date and time directly from the system clock.

Expected Output: (values will vary depending on the current system date and time)

Current Date = 2026-07-08
Current Date and Time = 2026-07-08T10:15:30.123456
▼ Hint
  • Use LocalDate.now() to get today’s date.
  • Use LocalDateTime.now() to get the current date and time together.
  • Print both objects directly; their toString() gives a readable ISO-8601 format.
▼ Solution & Explanation

Solution:

import java.time.LocalDate;
import java.time.LocalDateTime;

public class Main {
    public static void main(String[] args) {
        LocalDate currentDate = LocalDate.now();
        LocalDateTime currentDateTime = LocalDateTime.now();

        System.out.println("Current Date = " + currentDate);
        System.out.println("Current Date and Time = " + currentDateTime);
    }
}Code language: Java (java)

Explanation:

  • LocalDate.now(): Returns the current date from the system clock in the default time zone, without time information.
  • LocalDateTime.now(): Returns the current date combined with the current time, down to nanosecond precision.
  • Note: Since these methods read the live system clock, the printed values will be different each time you run the program.

Exercise 59: Calculate the Difference Between Two Dates

Practice Problem: Write a Java program to calculate the difference between two given dates in years, months, and days using the Period class.

Purpose: This exercise helps you practice using the Period class to measure the interval between two LocalDate objects, useful for age calculators, deadline trackers, and scheduling logic.

Given Input: startDate = 2015-06-15, endDate = 2023-09-10

Expected Output:

Years = 8
Months = 2
Days = 26
▼ Hint
  • Create two LocalDate objects using LocalDate.of() for the start and end dates.
  • Use Period.between(start, end) to calculate the interval.
  • Call getYears(), getMonths(), and getDays() on the Period object.
  • Print each value with a descriptive label.
▼ Solution & Explanation

Solution:

import java.time.LocalDate;
import java.time.Period;

public class Main {
    public static void main(String[] args) {
        LocalDate startDate = LocalDate.of(2015, 6, 15);
        LocalDate endDate = LocalDate.of(2023, 9, 10);

        Period period = Period.between(startDate, endDate);

        System.out.println("Years = " + period.getYears());
        System.out.println("Months = " + period.getMonths());
        System.out.println("Days = " + period.getDays());
    }
}Code language: Java (java)

Explanation:

  • LocalDate.of(2015, 6, 15): Creates a LocalDate object representing a specific year, month, and day.
  • Period.between(startDate, endDate): Calculates the difference between two dates as a Period object containing years, months, and days.
  • period.getYears(): Extracts each component of the calculated period (years, months, days) separately for display.

Exercise 60: Add or Subtract Days from a Given Date

Practice Problem: Write a Java program to add and subtract a given number of days from a date using the plusDays() and minusDays() methods.

Purpose: This exercise helps you practice date arithmetic with the LocalDate class, useful for calculating deadlines, due dates, and reminders.

Given Input: date = 2026-03-15, add 10 days, subtract 5 days

Expected Output:

New Date after Adding = 2026-03-25
New Date after Subtracting = 2026-03-10
▼ Hint
  • Create a LocalDate object for the given date.
  • Use plusDays(n) to get a new date n days later.
  • Use minusDays(n) to get a new date n days earlier.
  • Remember that LocalDate is immutable, so each method returns a new object instead of modifying the original.
▼ Solution & Explanation

Solution:

import java.time.LocalDate;

public class Main {
    public static void main(String[] args) {
        LocalDate date = LocalDate.of(2026, 3, 15);

        LocalDate newDateAfterAdding = date.plusDays(10);
        LocalDate newDateAfterSubtracting = date.minusDays(5);

        System.out.println("New Date after Adding = " + newDateAfterAdding);
        System.out.println("New Date after Subtracting = " + newDateAfterSubtracting);
    }
}Code language: Java (java)

Explanation:

  • date.plusDays(10): Returns a new LocalDate that is 10 days after the original date.
  • date.minusDays(5): Returns a new LocalDate that is 5 days before the original date.
  • Immutability: LocalDate never changes in place. Each method call produces a fresh LocalDate instance, leaving the original date unchanged.

Exercise 61: Format a Date Using DateTimeFormatter

Practice Problem: Write a Java program to format a given date into the “dd-MM-yyyy” pattern using the DateTimeFormatter class.

Purpose: This exercise helps you practice using DateTimeFormatter to convert a LocalDate into a custom string representation, a common requirement when displaying dates in reports and user interfaces.

Given Input: date = 2026-12-25

Expected Output: Formatted Date = 25-12-2026

▼ Hint

Create a DateTimeFormatter with the pattern “dd-MM-yyyy” using ofPattern(), then call format() on the LocalDate object, passing the formatter.

▼ Solution & Explanation

Solution:

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;

public class Main {
    public static void main(String[] args) {
        LocalDate date = LocalDate.of(2026, 12, 25);

        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd-MM-yyyy");
        String formattedDate = date.format(formatter);

        System.out.println("Formatted Date = " + formattedDate);
    }
}Code language: Java (java)

Explanation:

  • DateTimeFormatter.ofPattern("dd-MM-yyyy"): Creates a formatter that defines how the date should be displayed, day first, then month, then year.
  • date.format(formatter): Converts the LocalDate into a String using the given formatter pattern.
  • "Formatted Date = " + formattedDate: Concatenates the label with the resulting formatted string for display.

Exercise 62: Write Text to a File Using FileWriter

Practice Problem: Write a Java program to write a given text to a file using the FileWriter class.

Purpose: This exercise helps you practice basic file writing operations in Java, including handling checked exceptions with try-catch, a foundational skill for working with persistent data.

Given Input: fileName = "output.txt", text = "Hello, this is a sample file."

Expected Output: Data written to the file successfully.

▼ Hint
  • Create a FileWriter object by passing the file name to its constructor.
  • Use the write() method to write the given text to the file.
  • Use try-with-resources so the file is closed automatically after writing.
  • Wrap the file operations in a try-catch block to handle IOException.
▼ Solution & Explanation

Solution:

import java.io.FileWriter;
import java.io.IOException;

public class Main {
    public static void main(String[] args) {
        String fileName = "output.txt";
        String text = "Hello, this is a sample file.";

        try (FileWriter writer = new FileWriter(fileName)) {
            writer.write(text);
            System.out.println("Data written to the file successfully.");
        } catch (IOException e) {
            System.out.println("An error occurred while writing to the file.");
        }
    }
}Code language: Java (java)

Explanation:

  • new FileWriter(fileName): Creates a FileWriter object that opens (or creates) the specified file for writing.
  • try (FileWriter writer = ...): Uses try-with-resources so the file is automatically closed once the block finishes.
  • writer.write(text): Writes the given string content to the file.
  • catch (IOException e): Catches any input/output error, such as an invalid file path, and prevents the program from crashing.

Exercise 63: Read Content from a File Using BufferedReader

Practice Problem: Write a Java program to read and print the content of a text file line by line using the BufferedReader class.

Purpose: This exercise helps you practice reading file content efficiently using BufferedReader, which buffers input to reduce the number of read operations, and reinforces exception handling with IOException.

Given Input: fileName = "output.txt", containing the text "Hello, this is a sample file."

Expected Output: Hello, this is a sample file.

▼ Hint
  • Create a FileReader wrapped inside a BufferedReader for efficient reading.
  • Use readLine() inside a loop to read the file line by line until it returns null.
  • Print each line as it is read.
  • Handle IOException using a try-catch block or try-with-resources.
▼ Solution & Explanation

Solution:

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

public class Main {
    public static void main(String[] args) {
        String fileName = "output.txt";

        try (BufferedReader reader = new BufferedReader(new FileReader(fileName))) {
            String line;
            while ((line = reader.readLine()) != null) {
                System.out.println(line);
            }
        } catch (IOException e) {
            System.out.println("An error occurred while reading the file.");
        }
    }
}Code language: Java (java)

Explanation:

  • new BufferedReader(new FileReader(fileName)): Wraps a FileReader inside a BufferedReader to read text efficiently using an internal buffer.
  • reader.readLine(): Reads one line of text at a time and returns null when the end of the file is reached.
  • while ((line = reader.readLine()) != null): Assigns each line to the variable line and continues looping until there is nothing left to read.
  • catch (IOException e): Handles errors such as a missing file or a restricted file path.

Exercise 64: Append Data to an Existing File

Practice Problem: Write a Java program to append additional text to the end of an existing file without overwriting its current content.

Purpose: This exercise helps you practice using FileWriter in append mode, useful for logging, accumulating records, and adding entries to a file over time without losing previous data.

Given Input: fileName = "output.txt", textToAppend = "This line was appended."

Expected Output: Data appended to the file successfully.

▼ Hint

Pass true as the second argument to the FileWriter constructor to open the file in append mode instead of overwrite mode.

▼ Solution & Explanation

Solution:

import java.io.FileWriter;
import java.io.IOException;

public class Main {
    public static void main(String[] args) {
        String fileName = "output.txt";
        String textToAppend = "This line was appended.";

        try (FileWriter writer = new FileWriter(fileName, true)) {
            writer.write(System.lineSeparator() + textToAppend);
            System.out.println("Data appended to the file successfully.");
        } catch (IOException e) {
            System.out.println("An error occurred while appending to the file.");
        }
    }
}Code language: Java (java)

Explanation:

  • new FileWriter(fileName, true): The second argument true enables append mode, so existing content in the file is preserved.
  • System.lineSeparator() + textToAppend: Adds a new line before the appended text so it does not run into the previous content.
  • catch (IOException e): Handles any error that occurs while accessing or writing to the file.

Filed Under: Java Exercises

Did you find this page helpful? Let others know about it. Sharing helps me continue to create free Python resources.

TweetF  sharein  shareP  Pin

About Vishal

I’m Vishal Hule, the Founder of PYnative.com. As a Python developer, I enjoy assisting students, developers, and learners. Follow me on Twitter.

Related Tutorial Topics:

Java Exercises

All Coding Exercises:

C Exercises
C++ Exercises
Python Exercises
Java Exercises
C# Exercises

Python Exercises and Quizzes

Free coding exercises and quizzes cover Python basics, data structure, data analytics, and more.

  • 15+ Topic-specific Exercises and Quizzes
  • Each Exercise contains 25+ questions
  • Each Quiz contains 25 MCQ
Exercises
Quizzes

Leave a Reply Cancel reply

your email address will NOT be published. all comments are moderated according to our comment policy.

Use <pre> tag for posting code. E.g. <pre> Your entire code </pre>

In: Java Exercises
TweetF  sharein  shareP  Pin

  Java Exercises

  • All Java Exercises
  • Java Exercise for Beginners
  • Java Loops Exercise
  • Java String Exercise
  • Java ArrayList Exercise
  • Java LinkedList Exercise
  • Java HashMap and TreeMap Exercise
  • Java HashSet and TreeSet Exercise
  • Java OOP Exercise
  • Java Methods Exercise
  • Java Enums Exercise
  • Java Exception Handling Exercise
  • Java File Handling Exercise
  • Java Date and Time Exercise
  • Java Data Structures Exercise
  • Java Sorting and Searching Exercise
  • Java Lambda and Functional Interfaces Exercise
  • Java Regex Exercise
  • Java Random Data Generation Exercise
  • Java Generics Exercise
  • Java Reflection Exercise
  • Java JDBC Exercise

All Coding Exercises

Python Exercises C Exercises C++ Exercises Java Exercises C# Exercises

About PYnative

PYnative.com is for Python lovers. Here, You can get Tutorials, Exercises, and Quizzes to practice and improve your Python skills.

Follow Us

To get New Python Tutorials, Exercises, and Quizzes

  • Twitter
  • Facebook
  • Sitemap

Explore Python

  • Learn Python
  • Python Basics
  • Python Databases
  • Python Exercises
  • Python Quizzes
  • Online Python Code Editor
  • Python Tricks

Coding Exercises

  • C Exercises
  • C++ Exercises
  • Python Exercises
  • Java Exercises
  • C# Exercises

Legal Stuff

  • About Us
  • Contact Us

We use cookies to improve your experience. While using PYnative, you agree to have read and accepted our:

  • Terms Of Use
  • Privacy Policy
  • Cookie Policy

Copyright © 2018–2026 pynative.com