Struggling to move from “I understand the syntax” to actually building real applications with Java? That gap between learning and doing can feel frustrating, but there’s a proven way to bridge it: deliberate, hands-on practice. This post is designed to make that leap feel natural and rewarding.
We’ve gathered 100 Java practice problems with clear, step-by-step solutions to help you write code with genuine confidence. You’ll start with core fundamentals like variables, loops, and methods, then progress to object-oriented programming, collections, exception handling, file I/O, and algorithmic challenges. Every problem is written in plain, simple language—try it on your own first, then check the solution to deeply understand the logic behind it.
Why is practice so crucial? Programming is a craft. Every problem you solve builds mental muscle memory, sharpens your debugging skills, and turns abstract concepts into automatic habits. Regular practice is what separates developers who merely read code from those who can design, build, and troubleshoot real-world applications. It’s also the secret to acing coding interviews, where live problem-solving is often the deciding factor.
Whether you’re a complete beginner finding your footing in Java or a developer preparing for a technical interview, these exercises will make your learning stick. Pick a problem, get coding, and experience that amazing “I’m really getting this!” feeling. Your path to Java mastery starts right here.
Also try it: 100 kotlin practice problems with solutions
1. Write a program that prints “Hello, World!” to the console.
java
public class Main {
public static void main(String[] args) {
System.out.println("Hello, World!");
}
}
2. Write a program that declares two integer variables, assigns them values, and prints their sum.
java
public class Main {
public static void main(String[] args) {
int a = 10;
int b = 20;
int sum = a + b;
System.out.println("Sum: " + sum);
}
}
3. Write a program that takes an integer input from the user and prints whether it is even or odd.
java
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter a number: ");
int num = sc.nextInt();
if (num % 2 == 0)
System.out.println(num + " is even");
else
System.out.println(num + " is odd");
sc.close();
}
}
4. Write a program that prints the numbers from 1 to 10 using a for loop.
java
public class Main {
public static void main(String[] args) {
for (int i = 1; i <= 10; i++) {
System.out.print(i + " ");
}
}
}
5. Write a program that prints the factorial of a given number (e.g., 5).
java
public class Main {
public static void main(String[] args) {
int n = 5;
int fact = 1;
for (int i = 1; i <= n; i++) {
fact *= i;
}
System.out.println("Factorial of " + n + " is " + fact);
}
}
6. Write a program to reverse a string (e.g., “Hello” → “olleH”).
java
public class Main {
public static void main(String[] args) {
String str = "Hello";
String reversed = new StringBuilder(str).reverse().toString();
System.out.println(reversed);
}
}
7. Write a program to check if a string is a palindrome (e.g., “radar”).
java
public class Main {
public static void main(String[] args) {
String str = "radar";
String reversed = new StringBuilder(str).reverse().toString();
if (str.equals(reversed))
System.out.println(str + " is palindrome");
else
System.out.println(str + " is not palindrome");
}
}
8. Write a program to find the largest element in an array {3, 7, 1, 9, 4}.
java
public class Main {
public static void main(String[] args) {
int[] arr = {3, 7, 1, 9, 4};
int max = arr[0];
for (int num : arr) {
if (num > max) max = num;
}
System.out.println("Largest: " + max);
}
}
9. Write a program to calculate the sum of all elements in an array {2,4,6,8}.
java
public class Main {
public static void main(String[] args) {
int[] arr = {2,4,6,8};
int sum = 0;
for (int num : arr) sum += num;
System.out.println("Sum: " + sum);
}
}
10. Write a program that counts the number of vowels in a string “Hello World”.
java
public class Main {
public static void main(String[] args) {
String str = "Hello World";
int count = 0;
for (char c : str.toLowerCase().toCharArray()) {
if ("aeiou".indexOf(c) != -1) count++;
}
System.out.println("Number of vowels: " + count);
}
}
11. Write a program that prints the Fibonacci series up to 10 terms.
java
public class Main {
public static void main(String[] args) {
int n = 10, a = 0, b = 1;
System.out.print("Fibonacci: ");
for (int i = 0; i < n; i++) {
System.out.print(a + " ");
int next = a + b;
a = b;
b = next;
}
}
}
12. Write a program that checks if a given number is prime (e.g., 17).
java
public class Main {
public static void main(String[] args) {
int num = 17;
boolean isPrime = true;
if (num <= 1) isPrime = false;
else {
for (int i = 2; i <= Math.sqrt(num); i++) {
if (num % i == 0) {
isPrime = false;
break;
}
}
}
System.out.println(num + (isPrime ? " is prime" : " is not prime"));
}
}
13. Write a program to remove duplicate elements from an array {1,2,2,3,4,4,5}.
java
import java.util.*;
public class Main {
public static void main(String[] args) {
int[] arr = {1,2,2,3,4,4,5};
Set<Integer> set = new LinkedHashSet<>();
for (int num : arr) set.add(num);
System.out.println(set);
}
}
14. Write a program that sorts an array {5,2,8,1,3} in ascending order.
java
import java.util.Arrays;
public class Main {
public static void main(String[] args) {
int[] arr = {5,2,8,1,3};
Arrays.sort(arr);
System.out.println(Arrays.toString(arr));
}
}
15. Write a program that finds the second largest number in an array {10,20,4,45,99}.
java
import java.util.Arrays;
public class Main {
public static void main(String[] args) {
int[] arr = {10,20,4,45,99};
Arrays.sort(arr);
System.out.println("Second largest: " + arr[arr.length-2]);
}
}
16. Write a function that returns the greatest common divisor (GCD) of two numbers.
java
public class Main {
public static int gcd(int a, int b) {
while (b != 0) {
int temp = b;
b = a % b;
a = temp;
}
return a;
}
public static void main(String[] args) {
System.out.println(gcd(48, 18));
}
}
17. Write a class Rectangle with fields length and width, a constructor, and a method to compute area.
java
class Rectangle {
double length, width;
Rectangle(double length, double width) {
this.length = length;
this.width = width;
}
double area() {
return length * width;
}
}
public class Main {
public static void main(String[] args) {
Rectangle r = new Rectangle(5, 3);
System.out.println("Area: " + r.area());
}
}
18. Write a program that demonstrates method overloading by creating two add methods (one for ints, one for doubles).
java
public class Main {
static int add(int a, int b) { return a + b; }
static double add(double a, double b) { return a + b; }
public static void main(String[] args) {
System.out.println(add(5, 10));
System.out.println(add(2.5, 3.7));
}
}
19. Write a program that creates a Student class with name and roll number, then prints the object’s details.
java
class Student {
String name;
int roll;
Student(String name, int roll) {
this.name = name;
this.roll = roll;
}
void display() {
System.out.println("Name: " + name + ", Roll: " + roll);
}
}
public class Main {
public static void main(String[] args) {
Student s = new Student("Alice", 101);
s.display();
}
}
20. Write a program that uses inheritance: a base class Animal with a method sound(), and a derived class Dog that overrides it.
java
class Animal {
void sound() { System.out.println("Animal makes sound"); }
}
class Dog extends Animal {
@Override
void sound() { System.out.println("Dog barks"); }
}
public class Main {
public static void main(String[] args) {
Animal a = new Dog();
a.sound();
}
}
21. Write a program that uses an interface Drawable with a method draw(), and a class Circle that implements it.
java
interface Drawable {
void draw();
}
class Circle implements Drawable {
public void draw() { System.out.println("Drawing Circle"); }
}
public class Main {
public static void main(String[] args) {
Drawable d = new Circle();
d.draw();
}
}
22. Write a program that handles division by zero using try-catch.
java
public class Main {
public static void main(String[] args) {
try {
int result = 10 / 0;
} catch (ArithmeticException e) {
System.out.println("Cannot divide by zero!");
}
}
}
23. Write a program that reads a line from the user and prints its length.
java
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter a string: ");
String line = sc.nextLine();
System.out.println("Length: " + line.length());
sc.close();
}
}
24. Write a program that counts the number of words in a sentence using split.
java
public class Main {
public static void main(String[] args) {
String sentence = "The quick brown fox";
String[] words = sentence.split(" ");
System.out.println("Word count: " + words.length);
}
}
25. Write a program that converts a list of strings to uppercase using loops.
java
import java.util.*;
public class Main {
public static void main(String[] args) {
List<String> list = Arrays.asList("apple", "banana", "cherry");
for (int i = 0; i < list.size(); i++) {
System.out.print(list.get(i).toUpperCase() + " ");
}
}
}
26. Write a program that uses an ArrayList to store 5 integers and then prints them.
java
import java.util.ArrayList;
public class Main {
public static void main(String[] args) {
ArrayList<Integer> list = new ArrayList<>();
for (int i = 1; i <= 5; i++) list.add(i);
System.out.println(list);
}
}
27. Write a program that checks if a given string contains only digits.
java
public class Main {
public static void main(String[] args) {
String str = "12345";
boolean onlyDigits = str.matches("\\d+");
System.out.println(onlyDigits);
}
}
28. Write a program that finds the common elements between two integer arrays.
java
import java.util.*;
public class Main {
public static void main(String[] args) {
int[] arr1 = {1,2,3,4};
int[] arr2 = {3,4,5,6};
Set<Integer> set = new HashSet<>();
for (int num : arr1) set.add(num);
for (int num : arr2) {
if (set.contains(num)) System.out.print(num + " ");
}
}
}
29. Write a program that squares each element of an array using a lambda expression.
java
import java.util.Arrays;
public class Main {
public static void main(String[] args) {
int[] arr = {1,2,3,4};
Arrays.stream(arr).map(x -> x * x).forEach(System.out::println);
}
}
30. Write a program that writes a string to a file named “output.txt” and then reads it back.
java
import java.nio.file.*;
public class Main {
public static void main(String[] args) throws Exception {
String content = "Hello Java";
Files.write(Paths.get("output.txt"), content.getBytes());
String read = new String(Files.readAllBytes(Paths.get("output.txt")));
System.out.println(read);
}
}
31. Write a program that uses recursion to compute the factorial of a number.
java
public class Main {
static int fact(int n) {
if (n <= 1) return 1;
return n * fact(n - 1);
}
public static void main(String[] args) {
System.out.println(fact(5));
}
}
Also try it: 100 C# practice problems with solutions
32. Write a program that prints a multiplication table (1 to 10) for a given number.
java
public class Main {
public static void main(String[] args) {
int n = 7;
for (int i = 1; i <= 10; i++) {
System.out.println(n + " x " + i + " = " + (n * i));
}
}
}
33. Write a program that removes all whitespace from a string.
java
public class Main {
public static void main(String[] args) {
String str = " Hello World ";
String trimmed = str.replaceAll("\\s", "");
System.out.println(trimmed);
}
}
34. Write a program that swaps two numbers without using a third variable.
java
public class Main {
public static void main(String[] args) {
int a = 5, b = 10;
a = a + b;
b = a - b;
a = a - b;
System.out.println("a=" + a + ", b=" + b);
}
}
35. Write a program that creates a HashMap to store name-age pairs and prints them.
java
import java.util.HashMap;
public class Main {
public static void main(String[] args) {
HashMap<String, Integer> map = new HashMap<>();
map.put("Alice", 25);
map.put("Bob", 30);
for (var entry : map.entrySet()) {
System.out.println(entry.getKey() + ": " + entry.getValue());
}
}
}
36. Write a program that sorts a list of strings alphabetically.
java
import java.util.*;
public class Main {
public static void main(String[] args) {
List<String> list = Arrays.asList("banana", "apple", "cherry");
Collections.sort(list);
System.out.println(list);
}
}
37. Write a program that finds the first non-repeated character in a string “swiss”.
java
import java.util.LinkedHashMap;
import java.util.Map;
public class Main {
public static void main(String[] args) {
String str = "swiss";
Map<Character, Integer> map = new LinkedHashMap<>();
for (char c : str.toCharArray()) {
map.put(c, map.getOrDefault(c, 0) + 1);
}
for (var entry : map.entrySet()) {
if (entry.getValue() == 1) {
System.out.println(entry.getKey());
break;
}
}
}
}
38. Write a program that checks if two strings are anagrams (e.g., “listen” and “silent”).
java
import java.util.Arrays;
public class Main {
public static void main(String[] args) {
String s1 = "listen";
String s2 = "silent";
char[] c1 = s1.toCharArray();
char[] c2 = s2.toCharArray();
Arrays.sort(c1);
Arrays.sort(c2);
System.out.println(Arrays.equals(c1, c2));
}
}
39. Write a program that implements a simple counter using a static variable.
java
public class Counter {
static int count = 0;
Counter() { count++; }
public static void main(String[] args) {
new Counter();
new Counter();
System.out.println("Objects created: " + count);
}
}
40. Write a program that prints the current date and time using LocalDateTime.
java
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
public class Main {
public static void main(String[] args) {
LocalDateTime now = LocalDateTime.now();
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
System.out.println(now.format(formatter));
}
}
41. Write a program that rotates an array to the left by k positions (k=2).
java
import java.util.Arrays;
public class Main {
public static void main(String[] args) {
int[] arr = {1,2,3,4,5};
int k = 2;
k %= arr.length;
int[] temp = new int[arr.length];
for (int i = 0; i < arr.length; i++) {
int newIndex = (i - k + arr.length) % arr.length;
temp[newIndex] = arr[i];
}
System.out.println(Arrays.toString(temp));
}
}
42. Write a program that finds the missing number in an array of 1..n (e.g., {1,2,3,5} missing 4).
java
public class Main {
public static void main(String[] args) {
int[] arr = {1,2,3,5};
int n = 5;
int totalSum = n * (n + 1) / 2;
int arrSum = 0;
for (int num : arr) arrSum += num;
System.out.println("Missing: " + (totalSum - arrSum));
}
}
43. Write a program that counts the occurrences of each character in a string using HashMap.
java
import java.util.HashMap;
public class Main {
public static void main(String[] args) {
String str = "abracadabra";
HashMap<Character, Integer> map = new HashMap<>();
for (char c : str.toCharArray()) {
map.put(c, map.getOrDefault(c, 0) + 1);
}
System.out.println(map);
}
}
44. Write a program that merges two sorted arrays into one sorted array.
java
import java.util.Arrays;
public class Main {
public static void main(String[] args) {
int[] a = {1,3,5};
int[] b = {2,4,6};
int[] merged = new int[a.length + b.length];
int i=0, j=0, k=0;
while (i < a.length && j < b.length) {
if (a[i] < b[j]) merged[k++] = a[i++];
else merged[k++] = b[j++];
}
while (i < a.length) merged[k++] = a[i++];
while (j < b.length) merged[k++] = b[j++];
System.out.println(Arrays.toString(merged));
}
}
45. Write a program that uses the Math class to compute the square root of a number.
java
public class Main {
public static void main(String[] args) {
double num = 25;
double sqrt = Math.sqrt(num);
System.out.println(sqrt);
}
}
46. Write a program that throws a custom exception when a negative number is passed to a method.
java
class NegativeNumberException extends Exception {}
public class Main {
static void checkPositive(int n) throws NegativeNumberException {
if (n < 0) throw new NegativeNumberException();
System.out.println("Valid");
}
public static void main(String[] args) {
try {
checkPositive(-5);
} catch (NegativeNumberException e) {
System.out.println("Caught negative number exception");
}
}
}
47. Write a program that simulates a simple ATM with balance check and withdraw.
java
import java.util.Scanner;
public class ATM {
private double balance = 1000;
void withdraw(double amount) {
if (amount <= balance) {
balance -= amount;
System.out.println("Withdrawn: " + amount);
} else {
System.out.println("Insufficient balance");
}
}
public static void main(String[] args) {
ATM atm = new ATM();
atm.withdraw(200);
System.out.println("Balance: " + atm.balance);
}
}
48. Write a program that computes the power of a number using recursion (x^n).
java
public class Main {
static int power(int base, int exp) {
if (exp == 0) return 1;
return base * power(base, exp - 1);
}
public static void main(String[] args) {
System.out.println(power(2, 5));
}
}
49. Write a program that checks if a string is a valid palindrome considering only alphanumeric characters.
java
public class Main {
public static void main(String[] args) {
String s = "A man, a plan, a canal: Panama";
String cleaned = s.replaceAll("[^a-zA-Z0-9]", "").toLowerCase();
String reversed = new StringBuilder(cleaned).reverse().toString();
System.out.println(cleaned.equals(reversed));
}
}
50. Write a program that creates a simple thread by extending Thread class.
java
class MyThread extends Thread {
public void run() {
System.out.println("Thread running");
}
}
public class Main {
public static void main(String[] args) {
MyThread t = new MyThread();
t.start();
}
}
51. Write a program that creates a thread by implementing Runnable.
java
class MyRunnable implements Runnable {
public void run() {
System.out.println("Runnable thread");
}
}
public class Main {
public static void main(String[] args) {
Thread t = new Thread(new MyRunnable());
t.start();
}
}
52. Write a program that uses synchronized keyword to prevent race condition on a counter.
java
class Counter {
private int count = 0;
synchronized void increment() { count++; }
int getCount() { return count; }
}
public class Main {
public static void main(String[] args) throws Exception {
Counter c = new Counter();
Thread t1 = new Thread(() -> { for(int i=0;i<1000;i++) c.increment(); });
Thread t2 = new Thread(() -> { for(int i=0;i<1000;i++) c.increment(); });
t1.start(); t2.start();
t1.join(); t2.join();
System.out.println(c.getCount());
}
}
53. Write a program that reads all lines from a text file and prints them.
java
import java.nio.file.*;
public class Main {
public static void main(String[] args) throws Exception {
Files.lines(Paths.get("input.txt")).forEach(System.out::println);
}
}
54. Write a program that writes a list of strings to a file using BufferedWriter.
java
import java.io.*;
public class Main {
public static void main(String[] args) throws IOException {
try (BufferedWriter bw = new BufferedWriter(new FileWriter("output.txt"))) {
bw.write("Hello");
bw.newLine();
bw.write("World");
}
}
}
55. Write a program that sorts a map by values.
java
import java.util.*;
public class Main {
public static void main(String[] args) {
Map<String, Integer> map = new HashMap<>();
map.put("A", 3);
map.put("B", 1);
map.put("C", 2);
List<Map.Entry<String, Integer>> list = new ArrayList<>(map.entrySet());
list.sort(Map.Entry.comparingByValue());
list.forEach(e -> System.out.println(e.getKey() + ":" + e.getValue()));
}
}
56. Write a program that implements a stack using an array.
java
class Stack {
private int[] arr;
private int top;
private int capacity;
Stack(int size) { arr = new int[size]; top = -1; capacity = size; }
void push(int x) { if (top < capacity-1) arr[++top] = x; }
int pop() { if (top >= 0) return arr[top--]; return -1; }
}
public class Main {
public static void main(String[] args) {
Stack s = new Stack(3);
s.push(10);
s.push(20);
System.out.println(s.pop());
}
}
57. Write a program that finds the longest common prefix in an array of strings.
java
public class Main {
public static void main(String[] args) {
String[] strs = {"flower","flow","flight"};
if (strs.length == 0) return;
String prefix = strs[0];
for (int i = 1; i < strs.length; i++) {
while (strs[i].indexOf(prefix) != 0) {
prefix = prefix.substring(0, prefix.length()-1);
if (prefix.isEmpty()) break;
}
}
System.out.println(prefix);
}
}
58. Write a program that converts a binary string to its decimal equivalent.
java
public class Main {
public static void main(String[] args) {
String binary = "1010";
int decimal = Integer.parseInt(binary, 2);
System.out.println(decimal);
}
}
59. Write a program that calculates the average of an array of doubles.
java
public class Main {
public static void main(String[] args) {
double[] arr = {1.5, 2.5, 3.5};
double sum = 0;
for (double d : arr) sum += d;
System.out.println("Average: " + sum / arr.length);
}
}
60. Write a program that uses Enum to represent days of the week and prints a day.
java
enum Day { MON, TUE, WED, THU, FRI, SAT, SUN }
public class Main {
public static void main(String[] args) {
Day d = Day.FRI;
System.out.println(d);
}
}
61. Write a program that prints all permutations of a string (e.g., “ABC”) using recursion.
java
import java.util.*;
public class Main {
static void permute(String str, String ans) {
if (str.isEmpty()) {
System.out.println(ans);
return;
}
for (int i = 0; i < str.length(); i++) {
char ch = str.charAt(i);
String rest = str.substring(0,i) + str.substring(i+1);
permute(rest, ans + ch);
}
}
public static void main(String[] args) {
permute("ABC", "");
}
}
62. Write a program that implements binary search on a sorted array.
java
public class Main {
static int binarySearch(int[] arr, int x) {
int l=0, r=arr.length-1;
while (l <= r) {
int mid = l + (r-l)/2;
if (arr[mid] == x) return mid;
if (arr[mid] < x) l = mid+1;
else r = mid-1;
}
return -1;
}
public static void main(String[] args) {
int[] arr = {2,5,8,12,16};
System.out.println(binarySearch(arr, 12));
}
}
63. Write a program that reverses a linked list (singly linked list).
java
class ListNode {
int val;
ListNode next;
ListNode(int val) { this.val = val; }
}
public class Main {
static ListNode reverse(ListNode head) {
ListNode prev = null, curr = head;
while (curr != null) {
ListNode next = curr.next;
curr.next = prev;
prev = curr;
curr = next;
}
return prev;
}
public static void main(String[] args) {
ListNode head = new ListNode(1);
head.next = new ListNode(2);
head.next.next = new ListNode(3);
ListNode rev = reverse(head);
while (rev != null) {
System.out.print(rev.val + " ");
rev = rev.next;
}
}
}
64. Write a program that uses Optional to avoid null pointer exceptions.
java
import java.util.Optional;
public class Main {
public static void main(String[] args) {
String name = null;
Optional<String> opt = Optional.ofNullable(name);
System.out.println(opt.orElse("Default"));
}
}
Also try it: 100 .NET practice problems with solutions
65. Write a program that uses Stream API to filter even numbers and sum them.
java
import java.util.Arrays;
public class Main {
public static void main(String[] args) {
int[] arr = {1,2,3,4,5,6};
int sum = Arrays.stream(arr).filter(n -> n%2==0).sum();
System.out.println(sum);
}
}
66. Write a program that finds the intersection of two sets.
java
import java.util.*;
public class Main {
public static void main(String[] args) {
Set<Integer> set1 = new HashSet<>(Arrays.asList(1,2,3));
Set<Integer> set2 = new HashSet<>(Arrays.asList(3,4,5));
set1.retainAll(set2);
System.out.println(set1);
}
}
67. Write a program that uses PriorityQueue to print elements in sorted order.
java
import java.util.PriorityQueue;
public class Main {
public static void main(String[] args) {
PriorityQueue<Integer> pq = new PriorityQueue<>();
pq.add(5); pq.add(1); pq.add(3);
while (!pq.isEmpty()) {
System.out.print(pq.poll() + " ");
}
}
}
68. Write a program that simulates a simple logging using java.util.logging.
java
import java.util.logging.Logger;
public class Main {
private static final Logger logger = Logger.getLogger(Main.class.getName());
public static void main(String[] args) {
logger.info("Application started");
}
}
69. Write a program that calculates the number of days between two dates using LocalDate.
java
import java.time.LocalDate;
import java.time.temporal.ChronoUnit;
public class Main {
public static void main(String[] args) {
LocalDate d1 = LocalDate.of(2024,1,1);
LocalDate d2 = LocalDate.of(2024,12,31);
long days = ChronoUnit.DAYS.between(d1, d2);
System.out.println(days);
}
}
70. Write a program that converts a list of integers to an array of ints.
java
import java.util.List;
public class Main {
public static void main(String[] args) {
List<Integer> list = List.of(1,2,3);
int[] arr = list.stream().mapToInt(i->i).toArray();
System.out.println(arr.length);
}
}
71. Write a program that uses an AtomicInteger for thread‑safe increment without synchronization.
java
import java.util.concurrent.atomic.AtomicInteger;
public class Main {
public static void main(String[] args) throws Exception {
AtomicInteger counter = new AtomicInteger(0);
Thread t1 = new Thread(() -> { for(int i=0;i<1000;i++) counter.incrementAndGet(); });
Thread t2 = new Thread(() -> { for(int i=0;i<1000;i++) counter.incrementAndGet(); });
t1.start(); t2.start();
t1.join(); t2.join();
System.out.println(counter.get());
}
}
72. Write a program that uses CompletableFuture to run a task asynchronously.
java
import java.util.concurrent.CompletableFuture;
public class Main {
public static void main(String[] args) throws Exception {
CompletableFuture.supplyAsync(() -> "Hello")
.thenApply(s -> s + " World")
.thenAccept(System.out::println)
.join();
}
}
73. Write a program that reads a JSON string and parses it using org.json (assuming library).
java
// Using org.json library (not built-in, but for demonstration)
// import org.json.JSONObject;
// public class Main {
// public static void main(String[] args) {
// JSONObject obj = new JSONObject("{\"name\":\"John\",\"age\":30}");
// System.out.println(obj.getString("name"));
// }
// }
// Alternative without external lib (simple parsing exercise):
public class Main {
public static void main(String[] args) {
String json = "{\"name\":\"John\",\"age\":30}";
// simplified: extract name value
String name = json.split("\"name\":\"")[1].split("\"")[0];
System.out.println(name);
}
}
74. Write a program that generates a random integer between 1 and 100.
java
import java.util.Random;
public class Main {
public static void main(String[] args) {
Random rand = new Random();
int num = rand.nextInt(100) + 1;
System.out.println(num);
}
}
75. Write a program that implements a simple calculator using a switch statement.
java
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter two numbers and an operator (+,-,*,/): ");
double a = sc.nextDouble();
double b = sc.nextDouble();
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 '/': result = a / b; break;
default: result = 0; System.out.println("Invalid operator");
}
System.out.println("Result: " + result);
sc.close();
}
}
76. Write a program that checks if a number is a perfect number (sum of divisors equals itself).
java
public class Main {
public static void main(String[] args) {
int num = 28;
int sum = 0;
for (int i = 1; i < num; i++) {
if (num % i == 0) sum += i;
}
System.out.println(num + (sum == num ? " is perfect" : " is not perfect"));
}
}
77. Write a program that uses instanceof to check object type.
java
class Animal {}
class Dog extends Animal {}
public class Main {
public static void main(String[] args) {
Animal a = new Dog();
System.out.println(a instanceof Dog);
}
}
78. Write a program that creates a StringBuilder and appends multiple strings.
java
public class Main {
public static void main(String[] args) {
StringBuilder sb = new StringBuilder();
sb.append("Hello ");
sb.append("World");
System.out.println(sb.toString());
}
}
79. Write a program that prints the prime numbers between 1 and 100.
java
public class Main {
static boolean isPrime(int n) {
if (n <= 1) return false;
for (int i = 2; i <= Math.sqrt(n); i++) {
if (n % i == 0) return false;
}
return true;
}
public static void main(String[] args) {
for (int i = 2; i <= 100; i++) {
if (isPrime(i)) System.out.print(i + " ");
}
}
}
80. Write a program that finds the length of the longest substring without repeating characters.
java
import java.util.HashSet;
public class Main {
public static void main(String[] args) {
String s = "abcabcbb";
int max = 0, left = 0;
HashSet<Character> set = new HashSet<>();
for (int right = 0; right < s.length(); right++) {
while (set.contains(s.charAt(right))) {
set.remove(s.charAt(left));
left++;
}
set.add(s.charAt(right));
max = Math.max(max, right - left + 1);
}
System.out.println(max);
}
}
81. Write a program that implements a simple producer‑consumer using BlockingQueue.
java
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
public class Main {
public static void main(String[] args) {
BlockingQueue<Integer> queue = new ArrayBlockingQueue<>(5);
Thread producer = new Thread(() -> {
try { for (int i = 0; i < 10; i++) queue.put(i); } catch (InterruptedException e) {}
});
Thread consumer = new Thread(() -> {
try { for (int i = 0; i < 10; i++) System.out.println(queue.take()); } catch (InterruptedException e) {}
});
producer.start(); consumer.start();
}
}
82. Write a program that uses Pattern and Matcher to find all email addresses in a string.
java
import java.util.regex.*;
public class Main {
public static void main(String[] args) {
String text = "Contact us at john@example.com and jane@example.org";
Pattern p = Pattern.compile("[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,}");
Matcher m = p.matcher(text);
while (m.find()) {
System.out.println(m.group());
}
}
}
83. Write a program that uses LocalTime to add 2 hours to the current time.
java
import java.time.LocalTime;
public class Main {
public static void main(String[] args) {
LocalTime now = LocalTime.now();
LocalTime later = now.plusHours(2);
System.out.println("Now: " + now + ", Later: " + later);
}
}
84. Write a program that sorts a list of students by their roll numbers using Comparator.
java
import java.util.*;
class Student {
int roll;
String name;
Student(int roll, String name) { this.roll = roll; this.name = name; }
public String toString() { return roll + ":" + name; }
}
public class Main {
public static void main(String[] args) {
List<Student> list = Arrays.asList(new Student(3,"A"), new Student(1,"B"), new Student(2,"C"));
list.sort(Comparator.comparingInt(s -> s.roll));
System.out.println(list);
}
}
85. Write a program that copies an array using System.arraycopy.
java
import java.util.Arrays;
public class Main {
public static void main(String[] args) {
int[] src = {1,2,3};
int[] dest = new int[3];
System.arraycopy(src, 0, dest, 0, src.length);
System.out.println(Arrays.toString(dest));
}
}
86. Write a program that implements a singleton class (thread‑safe lazy initialization).
java
class Singleton {
private static volatile Singleton instance;
private Singleton() {}
public static Singleton getInstance() {
if (instance == null) {
synchronized (Singleton.class) {
if (instance == null) instance = new Singleton();
}
}
return instance;
}
}
public class Main {
public static void main(String[] args) {
Singleton s1 = Singleton.getInstance();
Singleton s2 = Singleton.getInstance();
System.out.println(s1 == s2);
}
}
87. Write a program that uses BigDecimal to handle precise decimal calculations (avoid double errors).
java
import java.math.BigDecimal;
public class Main {
public static void main(String[] args) {
BigDecimal a = new BigDecimal("0.1");
BigDecimal b = new BigDecimal("0.2");
System.out.println(a.add(b)); // 0.3
}
}
88. Write a program that reads system properties like java.version.
java
public class Main {
public static void main(String[] args) {
System.out.println("Java version: " + System.getProperty("java.version"));
}
}
89. Write a program that converts a number from decimal to binary using Integer.toBinaryString.
java
public class Main {
public static void main(String[] args) {
int num = 10;
String binary = Integer.toBinaryString(num);
System.out.println(binary);
}
}
90. Write a program that uses java.util.Arrays to compare two arrays.
java
import java.util.Arrays;
public class Main {
public static void main(String[] args) {
int[] a = {1,2,3};
int[] b = {1,2,3};
System.out.println(Arrays.equals(a, b));
}
}
91. Write a program that implements a simple linked list (insert at end and display).
java
class Node {
int data;
Node next;
Node(int d) { data = d; }
}
class LinkedList {
Node head;
void append(int data) {
if (head == null) head = new Node(data);
else {
Node curr = head;
while (curr.next != null) curr = curr.next;
curr.next = new Node(data);
}
}
void print() {
Node curr = head;
while (curr != null) {
System.out.print(curr.data + " ");
curr = curr.next;
}
}
}
public class Main {
public static void main(String[] args) {
LinkedList list = new LinkedList();
list.append(1);
list.append(2);
list.append(3);
list.print();
}
}
92. Write a program that finds the first duplicate element in an array.
java
import java.util.HashSet;
public class Main {
public static void main(String[] args) {
int[] arr = {1,2,3,2,4};
HashSet<Integer> set = new HashSet<>();
for (int num : arr) {
if (set.contains(num)) {
System.out.println("First duplicate: " + num);
break;
}
set.add(num);
}
}
}
93. Write a program that moves all zeros in an array to the end preserving order.
java
import java.util.Arrays;
public class Main {
public static void main(String[] args) {
int[] arr = {0,1,0,3,12};
int index = 0;
for (int num : arr) {
if (num != 0) arr[index++] = num;
}
while (index < arr.length) arr[index++] = 0;
System.out.println(Arrays.toString(arr));
}
}
94. Write a program that implements a simple LRU cache using LinkedHashMap.
java
import java.util.LinkedHashMap;
import java.util.Map;
public class LRUCache<K,V> extends LinkedHashMap<K,V> {
private final int capacity;
public LRUCache(int capacity) {
super(capacity, 0.75f, true);
this.capacity = capacity;
}
@Override
protected boolean removeEldestEntry(Map.Entry<K,V> eldest) {
return size() > capacity;
}
public static void main(String[] args) {
LRUCache<String,Integer> cache = new LRUCache<>(2);
cache.put("a",1);
cache.put("b",2);
cache.get("a");
cache.put("c",3);
System.out.println(cache); // {a=1, c=3}
}
}
95. Write a program that uses java.util.Timer to schedule a task.
java
import java.util.Timer;
import java.util.TimerTask;
public class Main {
public static void main(String[] args) {
Timer timer = new Timer();
timer.schedule(new TimerTask() {
public void run() {
System.out.println("Task executed");
timer.cancel();
}
}, 2000);
}
}
96. Write a program that uses java.util.concurrent.ExecutorService to manage threads.
java
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class Main {
public static void main(String[] args) {
ExecutorService executor = Executors.newFixedThreadPool(3);
for (int i = 0; i < 5; i++) {
executor.submit(() -> System.out.println(Thread.currentThread().getName()));
}
executor.shutdown();
}
}
97. Write a program that computes the median of an array of integers.
java
import java.util.Arrays;
public class Main {
public static void main(String[] args) {
int[] arr = {3,7,1,9,4};
Arrays.sort(arr);
double median;
if (arr.length % 2 == 0) {
median = (arr[arr.length/2 - 1] + arr[arr.length/2]) / 2.0;
} else {
median = arr[arr.length/2];
}
System.out.println("Median: " + median);
}
}
98. Write a program that uses java.util.Scanner to read multiple integers until EOF.
java
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int sum = 0;
while (sc.hasNextInt()) {
sum += sc.nextInt();
}
System.out.println("Sum: " + sum);
sc.close();
}
}
99. Write a program that implements a simple banking system with deposit and withdrawal using encapsulation.
java
class BankAccount {
private double balance;
public void deposit(double amount) { balance += amount; }
public boolean withdraw(double amount) {
if (amount <= balance) { balance -= amount; return true; }
return false;
}
public double getBalance() { return balance; }
}
public class Main {
public static void main(String[] args) {
BankAccount acc = new BankAccount();
acc.deposit(500);
acc.withdraw(200);
System.out.println("Balance: " + acc.getBalance());
}
}
100. Write a program that prints a triangle pattern of stars for a given height (e.g., 5).
java
public class Main {
public static void main(String[] args) {
int height = 5;
for (int i = 1; i <= height; i++) {
for (int j = 1; j <= i; j++) {
System.out.print("* ");
}
System.out.println();
}
}
}
Final Thoughts
Completing these 100 Java practice problems with solutions is more than just coding—it’s a step toward becoming stronger, smarter, and more confident as a programmer. Every problem you solved made your logic sharper and your patience stronger.
At times, some questions may have felt difficult, but each challenge you faced helped you grow. Remember, great developers are not born—they are made through practice, mistakes, and continuous learning.
Keep coding, keep experimenting, and never be afraid of errors—they are proof that you are learning. Your journey with Java doesn’t end here; this is just the beginning of something bigger. Stay consistent, believe in your progress, and keep moving forward.