Table of Contents
Introduction: Why Java Still Matters
Java has been a foundational programming language for decades and continues to fuel countless applications—from enterprise software to mobile apps and embedded systems. In 2025, it remains a global favorite due to its versatility, security features, and extensive ecosystem. With the release of Java 21 and innovations like virtual threads (Project Loom), Java keeps evolving to meet modern development needs.
However, mastering Java isn’t about only reading books or watching tutorials; it’s about writing code and practicing consistently. This blog presents a curated set of Java exercises with explanations and solutions to help you build confidence and sharpen your skills.
Why Practice is Key to Mastery
1: What is the default value of a boolean in Java?
Learning programming is like learning any other skill—you must practice to get good at it. Reading theory gives you knowledge; regular coding practice transforms that knowledge into ability.
-
Practice helps internalize syntax and concepts.
-
Debugging your code teaches problem-solving.
-
Regular exercises prepare you for real-world projects and interviews.
Explore Free Coding Courses !
Take your first step toward mastering in-demand skills, acing interviews, and securing top-tier jobs with Entri's free coding courses.
👉 Explore Free Courses NowHow to Practice Java Effectively
-
Set a Consistent Schedule:Â Even 30 minutes daily is better than long, irregular sessions.
-
Start Simple:Â Begin with basic syntax, loops, and conditional statements.
-
Build Up Gradually:Â Move to classes, objects, collections, and exception handling.
-
Try Projects:Â Apply what you learn in small programs.
-
Review and Reflect:Â Compare your solutions with sample answers.
-
Seek Help When Stuck:Â Community forums like StackOverflow and coding platforms offer valuable support.
Learn Java as a module in Entri’s Full Stack Development course!
Essential Java Exercises with Solutions
To help you develop your Java skills proficiently, here’s an expanded list of core exercises complete with explanations and sample code.
1. Hello World Program
public class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello, Java 2025!");
}
}
Explanation: This simple program prints a message to the console, teaching the structure of a Java class and the main method. It’s your foundational step into Java coding.
2. Add Two Numbers
public class AddNumbers {
public static void main(String[] args) {
int num1 = 7, num2 = 13;
int sum = num1 + num2;
System.out.println("Sum: " + sum);
}
}
Explanation: Demonstrates how to declare variables, perform arithmetic operations, and print the result.
3. Swap Two Numbers Without a Temporary Variable
public class SwapNumbers {
public static void main(String[] args) {
int a = 10, b = 20;
a = a + b; // a now 30
b = a - b; // b now 10
a = a - b; // a now 20
System.out.println("a = " + a);
System.out.println("b = " + b);
}
}
Explanation: Shows a classic trick to swap values using arithmetic instead of a temporary variable.
4. Find Factorial of a Number
public class Factorial {
public static void main(String[] args) {
int num = 6;
long fact = 1;
for (int i = 1; i <= num; i++) {
fact *= i;
}
System.out.println("Factorial of " + num + " is " + fact);
}
}
Explanation: Uses a loop to iteratively calculate the factorial of a given number, demonstrating control flow and data types.
5. Check Prime Number
public class PrimeCheck {
public static void main(String[] args) {
int num = 29;
boolean isPrime = true;
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.");
}
}
Explanation: Teaches loops, conditions, and how to optimize by checking divisors only up to half the number.
Learn Java foundations through our free materials!
6. Reverse a String
public class StringReverse {
public static void main(String[] args) {
String input = "Java2025";
String reversed = "";
for (int i = input.length() - 1; i >= 0; i--) {
reversed += input.charAt(i);
}
System.out.println("Reversed String: " + reversed);
}
}
Explanation: Uses a loop to reverse a string character by character, showcasing string operations.
7. Find Largest Element in Array
public class LargestInArray {
public static void main(String[] args) {
int[] numbers = {10, 28, 5, 14, 33};
int max = numbers[0];
for (int num : numbers) {
if (num > max) max = num;
}
System.out.println("Largest element is " + max);
}
}
Explanation: Demonstrates iterating through arrays and comparison logic.
8. Remove Duplicates from Array
import java.util.HashSet;
public class RemoveDuplicates {
public static void main(String[] args) {
int[] array = {1, 3, 3, 5, 2, 2, 9};
HashSet<Integer> set = new HashSet<>();
for (int num : array) {
set.add(num);
}
System.out.println("Array without duplicates: " + set);
}
}
Explanation: Introduces collection framework usage to eliminate duplicate elements efficiently.
9. Calculate Simple Interest
public class SimpleInterest {
public static void main(String[] args) {
double principal = 15000;
double rate = 7.5; // Annual rate in percent
double time = 3; // Years
double interest = (principal * rate * time) / 100;
System.out.println("Simple Interest = " + interest);
}
}
Explanation: Applies arithmetic to calculate financial formulae.
10. Pattern Printing (Triangle of Stars)
public class StarPattern {
public static void main(String[] args) {
int rows = 4;
for (int i = 1; i <= rows; i++) {
for (int j = 1; j <= i; j++) {
System.out.print("* ");
}
System.out.println();
}
}
}
Explanation: Uses nested loops to print a right-angled triangle pattern, a staple in coding interviews.
These exercises cover foundational topics including variables, control structures, arrays, strings, collections, arithmetic, and loops. By working through and understanding these programs, beginners gain essential skills to confidently progress further in Java programming.
Intermediate and Advanced Exercises to Try
Enhance your Java skills by tackling these intermediate and advanced exercises. These challenges cover core Java concepts like object-oriented programming, collections, exception handling, and more. Detailed explanations and sample code will help you understand the underlying principles and best practices.
1. Find the Second Most Frequent Element in an Array
Problem:Â Given an array, find the element that appears the second most number of times.
import java.util.*;
public class SecondMostFrequent {
public static int findSecondMostFrequent(int[] arr) {
Map<Integer, Integer> freqMap = new HashMap<>();
for (int num : arr) {
freqMap.put(num, freqMap.getOrDefault(num,0) + 1);
}
// Create a list of entries sorted by frequency descending
List<Map.Entry<Integer, Integer>> list = new ArrayList<>(freqMap.entrySet());
list.sort((a, b) -> b.getValue() - a.getValue());
if (list.size() < 2) return -1; // No second most frequent element
return list.get(1).getKey();
}
public static void main(String[] args) {
int[] input = {1, 2, 3, 3, 2, 2, 1, 1, 1};
System.out.println("Second most frequent element: " + findSecondMostFrequent(input));
}
}
Output:
Second most frequent element: 2
2. Implement a Phonebook with HashMap
Problem: Create a phonebook application that allows storing, searching, adding, and deleting contacts using Java’s HashMap.
import java.util.*;
public class PhoneBook {
private Map<String, String> contacts = new HashMap<>();
public void addContact(String name, String number) {
contacts.put(name, number);
}
public String searchNumber(String name) {
return contacts.getOrDefault(name, "Contact not found");
}
public void deleteContact(String name) {
contacts.remove(name);
}
public void displayAll() {
for (var entry : contacts.entrySet()) {
System.out.println(entry.getKey() + ": " + entry.getValue());
}
}
public static void main(String[] args) {
PhoneBook pb = new PhoneBook();
pb.addContact("Alice", "123-456-7890");
pb.addContact("Bob", "987-654-3210");
System.out.println(pb.searchNumber("Alice"));
pb.deleteContact("Bob");
pb.displayAll();
}Â
3. Create a BankAccount Class with OOP Concepts
Problem:Â Design a class for a bank account supporting deposit, withdrawal, and balance query with access modifiers.
public class BankAccount {
private String owner;
private double balance;
public BankAccount(String owner, double balance) {
this.owner = owner;
this.balance = balance;
}
public void deposit(double amount) {
if(amount > 0) {
balance += amount;
System.out.println(amount + " deposited. New balance: " + balance);
} else {
System.out.println("Invalid deposit amount.");
}
}
public void withdraw(double amount) {
if(amount > 0 && amount <= balance) {
balance -= amount;
System.out.println(amount + " withdrawn. Remaining balance: " + balance);
} else {
System.out.println("Invalid withdrawal or insufficient funds.");
}
}
public double getBalance() {
return balance;
}
public static void main(String[] args) {
BankAccount acc = new BankAccount("John Doe", 500);
acc.deposit(150);
acc.withdraw(100);
System.out.println("Balance: " + acc.getBalance());
}Â
4. Exception Handling: Divide Two Numbers Safely
Problem:Â Write a program to divide two numbers and handle division by zero using exceptions.
import java.util.Scanner;
public class SafeDivide {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter numerator: ");
int numerator = sc.nextInt();
System.out.print("Enter denominator: ");
int denominator = sc.nextInt();
try {
int result = numerator / denominator;
System.out.println("Result: " + result);
} catch(ArithmeticException e) {
System.out.println("Error: Division by zero is not allowed.");
} finally {
sc.close();
}
}
}
5. Use Java 21 Record Classes
Problem: Use record
 to define an immutable data class representing a Person (name and age).
public record Person(String name, int age) {}
public class TestRecord {
public static void main(String[] args) {
Person p = new Person("Jane Doe", 28);
System.out.println(p.name() + " is " + p.age() + " years old.");
}
}
6. Implement Multi-threading with Virtual Threads (Project Loom)
Problem:Â Create multiple virtual threads that print messages concurrently.
public class VirtualThreadsDemo {
public static void main(String[] args) throws InterruptedException {
Runnable task = () -> System.out.println("Running in thread: " + Thread.currentThread());
Thread vt1 = Thread.startVirtualThread(task);
Thread vt2 = Thread.startVirtualThread(task);
vt1.join();
vt2.join();
}
}
7. Binary Search Algorithm Implementation
public class BinarySearch {
public static int binarySearch(int[] arr, int target) {
int left = 0, right = arr.length -1;
while(left <= right) {
int mid = left + (right - left) / 2;
if(arr[mid] == target) return mid;
else if(arr[mid] < target) left = mid + 1;
else right = mid - 1;
}
return -1;
}
public static void main(String[] args) {
int[] data = {2, 4, 6, 8, 10, 12};
int index = binarySearch(data, 8);
System.out.println("Index of 8 is: " + index);
}
}
8. Merge Sort Algorithm
public class MergeSort {
public void merge(int[] arr, int l, int m, int r) {
int n1 = m - l + 1;
int n2 = r - m;
int[] L = new int[n1];
int[] R = new int[n2];
for (int i=0; i<n1; ++i)
L[i] = arr[l + i];
for (int j=0; j<n2; ++j)
R[j] = arr[m + 1+ j];
int i = 0, j = 0;
int k = l;
while(i < n1 && j < n2) {
if(L[i] <= R[j]) {
arr[k] = L[i];
i++;
} else {
arr[k] = R[j];
j++;
}
k++;
}
while(i < n1) {
arr[k] = L[i];
i++; k++;
}
while(j < n2) {
arr[k] = R[j];
j++; k++;
}
}
public void sort(int[] arr, int l, int r) {
if(l < r) {
int m = (l+r)/2;
sort(arr, l, m);
sort(arr, m+1, r);
merge(arr, l, m, r);
}
}
public static void main(String[] args) {
int[] arr = {12, 11, 13, 5, 6, 7};
MergeSort ms = new MergeSort();
ms.sort(arr, 0, arr.length-1);
System.out.println("Sorted array:");
for(int num : arr) System.out.print(num + " ");
}
}
Explore Free Coding Courses !
Take your first step toward mastering in-demand skills, acing interviews, and securing top-tier jobs with Entri's free coding courses.
👉 Explore Free Courses NowAvoid These Common Mistakes
Learning Java can be fulfilling but also challenging, especially when beginners fall into common pitfalls. Knowing and avoiding these mistakes early can save time, frustration, and help you write cleaner, more reliable code.
1. Forgetting to Close Resources
When you open files, database connections, or network streams, always ensure you close them. Not closing these resources can cause memory leaks and resource exhaustion.
-
Use try-with-resources (introduced in Java 7) to automatically close resources, for example:
try (FileInputStream fis = new FileInputStream("file.txt")) {
// Work with file
} catch (IOException e) {
e.printStackTrace();
}
This ensures that fis
is closed automatically even if an exception occurs.
2. Misusing Null and Not Handling NullPointerException
Null references are a primary cause of crashes in Java applications.
-
Avoid returning or working with null collections or arrays; prefer empty ones.
-
Always perform null checks before calling methods on objects that may be null.
-
Use Optional introduced in Java 8 to handle nullable values safely:
Optional<String> optionalName = Optional.ofNullable(possibleNullName);
optionalName.ifPresent(System.out::println);
3. Ignoring Exception Handling or Overusing Catch Blocks
Beginners sometimes catch generic Exception
 or ignore exceptions entirely, which leads to uninformative or problematic code.
-
Catch only specific exceptions you expect.
-
Provide meaningful messages and handle exceptions properly.
-
Don’t swallow exceptions silently.
4. Writing Messy, Unreadable Code
-
Use proper indentation and spacing.
-
Name variables and methods clearly (avoid meaningless names).
-
Don’t write large methods; break code into reusable, understandable functions.
-
Comment purposefully—not excessively or too little.
Readable code helps you and others understand and maintain the program.
5. Confusing Primitive Types and Wrapper Classes
Java has primitive types (int
, double
) and wrapper classes (Integer
, Double
). Beginners often mix them, causing autoboxing issues or unexpected behavior.
-
Use primitives for performance unless you need collections or generics requiring wrappers.
-
Be aware ofÂ
NullPointerException
when unboxing wrappers.
Final Thoughts
Mastering Java in 2025 is about consistent practice with a progressive set of challenges. Start with syntax and small programs, then level up to projects and advanced topics. Utilize the rich ecosystem of coding platforms to test your skills and get feedback. Even though Entri no longer offers standalone Java courses, their modules within broader coding tracts can complement your learning well.
Write code daily, debug, and refine your skills. Each line of Java you write is one step closer to mastery and better career prospects. Happy coding!
Explore Free Coding Courses !
Take your first step toward mastering in-demand skills, acing interviews, and securing top-tier jobs with Entri's free coding courses.
👉 Explore Free Courses NowFrequently Asked Questions
How often should I practice Java?
Aim for at least 30 minutes daily or at minimum, several times a week for consistent progress.
What’s the best way to learn Java for beginners?
Start with core syntax, practice small programs, move to object-oriented concepts, and solve challenges regularly.
Where can I find good exercises with solutions?
Visit platforms like HackerRank, JetBrains Academy, and Exercism for curated exercises and solutions.
Are Entri’s Java courses still available?
Entri has transitioned to including Java modules within wider coding and software development courses rather than standalone Java classes.