PYnative

Practice Coding

  • Python ▼
    • Python Tutorials
    • Python Basics
    • Python Interview Q&As
  • Coding Exercises ▼
    • Python Exercises
    • C++ Exercises
    • C Programming Exercises
    • Java Exercises
    • C# Exercises
  • MCQs▼
    • Python MCQ Quizzes
    • Java MCQ Quizzes
    • C++ MCQ Quizzes
  • Compilers▼
    • Online Python Compiler
    • Online C Compiler
    • Online C++ Compiler
    • Online Java Compiler
    • Online C# Compiler
Home » Java Exercises » Intermediate Java Exercises: 60 Coding Problems with Solutions

Intermediate Java Exercises: 60 Coding Problems with Solutions

Updated on: November 26, 2026 | Leave a Comment

Java is one of the widely used programming languages, and many developers start with it because it is reliable and well structured. To truly master it, though, you need to go beyond the basics and solve intermediate and advanced coding problems. You also need to learn how to use advanced data structures, functional programming with streams and lambdas, and object-oriented design.

This article has a list of 60 intermediate Java coding questions. They focus mainly on loops, arrays, strings, the Collections Framework (ArrayList, HashMap, HashSet), OOP concepts, generics, exception handling, the Stream API, lambda expressions and functional interfaces, file handling with Java I/O and NIO, regular expressions, the Date and Time, and other miscellaneous topics.

These coding problems will improve your logic and coding skills, help you write cleaner and more efficient code, and prepare you for Java interviews.

  • Also, See: Java Exercises with over 20+ topic-wise sets and 660+ coding questions to practice.
  • Intermediate Java Quiz
  • Practice questions using our Online Java Compiler

Exercise 1: Library System with Book, Member, and Borrowing Logic

Problem Statement: Write a Java program that implements a simple library system with a Book class and a Member class. A member should be able to borrow a book if it is available, and return it afterward. Use encapsulation so that the book’s availability status cannot be changed directly from outside the class.

Purpose: This exercise helps you practice encapsulation by keeping fields private and exposing controlled behavior through methods, a core principle used when designing real world systems like library management, inventory tracking, and reservation systems.

Given Input: A Book titled “Effective Java” and a Member named “Vishal” who borrows it, then returns it.

Expected Output:

Vishal borrowed: Effective Java
Effective Java is currently not available.
Vishal returned: Effective Java
Effective Java is now available.
💡 Hint
  • Keep the available field in Book private and expose it only through a getter.
  • Add a borrow() method in Book that sets available to false only if it is currently true.
  • Add a returnBook() method in Book that sets available back to true.
  • In Member, call book.borrow() and book.returnBook() instead of modifying the field directly.
✅ Solution & Explanation

Solution:

class Book {
    private String title;
    private boolean available;

    public Book(String title) {
        this.title = title;
        this.available = true;
    }

    public String getTitle() {
        return title;
    }

    public boolean isAvailable() {
        return available;
    }

    public boolean borrow() {
        if (available) {
            available = false;
            return true;
        }
        return false;
    }

    public void returnBook() {
        available = true;
    }
}

class Member {
    private String name;

    public Member(String name) {
        this.name = name;
    }

    public void borrowBook(Book book) {
        if (book.borrow()) {
            System.out.println(name + " borrowed: " + book.getTitle());
        } else {
            System.out.println(book.getTitle() + " is currently not available.");
        }
    }

    public void returnBook(Book book) {
        book.returnBook();
        System.out.println(name + " returned: " + book.getTitle());
        System.out.println(book.getTitle() + " is now available.");
    }
}

public class LibrarySystem {
    public static void main(String[] args) {
        Book book = new Book("Effective Java");
        Member member = new Member("Vishal");

        member.borrowBook(book);
        member.borrowBook(book);
        member.returnBook(book);
    }
}Code language: Java (java)

Explanation:

  • private boolean available: Keeps the availability status hidden from outside classes so it can only change through defined methods.
  • borrow(): Checks the current availability, updates it, and returns a boolean so the caller knows whether the action succeeded.
  • returnBook(): Resets the availability flag back to true once the member returns the book.
  • member.borrowBook(book): Delegates the borrowing logic to the Book object instead of manipulating its fields directly, which is the essence of encapsulation.

Exercise 2: Abstract Shape Class with Circle, Rectangle, and Triangle

Problem Statement: Write a Java program that defines an abstract class Shape with abstract methods area() and perimeter(). Create Circle, Rectangle, and Triangle subclasses that implement these methods.

Purpose: This exercise helps you practice abstraction and method overriding, which are used when designing systems that need a common contract across different implementations, such as shapes, payment types, or notification channels.

Given Input: A Circle with radius 5, a Rectangle with width 4 and height 6, and a Triangle with base 3, height 4, and three sides 3, 4, 5.

Expected Output:

Circle -> Area: 78.54, Perimeter: 31.42
Rectangle -> Area: 24.00, Perimeter: 20.00
Triangle -> Area: 6.00, Perimeter: 12.00
💡 Hint
  • Declare abstract double area() and abstract double perimeter() in Shape.
  • Use Math.PI for circle calculations.
  • For the triangle area, use the base and height directly since they are given.
  • Store all shapes in a List[Shape] and loop through it to print results polymorphically.
✅ Solution & Explanation

Solution:

import java.util.ArrayList;
import java.util.List;
abstract class Shape {
    abstract double area();
    abstract double perimeter();
    abstract String name();
}
class Circle extends Shape {
    private double radius;
    public Circle(double radius) {
        this.radius = radius;
    }
    double area() {
        return Math.PI * radius * radius;
    }
    double perimeter() {
        return 2 * Math.PI * radius;
    }
    String name() {
        return "Circle";
    }
}
class Rectangle extends Shape {
    private double width, height;
    public Rectangle(double width, double height) {
        this.width = width;
        this.height = height;
    }
    double area() {
        return width * height;
    }
    double perimeter() {
        return 2 * (width + height);
    }
    String name() {
        return "Rectangle";
    }
}
class Triangle extends Shape {
    private double base, height, sideA, sideB, sideC;
    public Triangle(double base, double height, double sideA, double sideB, double sideC) {
        this.base = base;
        this.height = height;
        this.sideA = sideA;
        this.sideB = sideB;
        this.sideC = sideC;
    }
    double area() {
        return 0.5 * base * height;
    }
    double perimeter() {
        return sideA + sideB + sideC;
    }
    String name() {
        return "Triangle";
    }
}
public class ShapeDemo {
    public static void main(String[] args) {
        List<Shape> shapes = new ArrayList<>();
        shapes.add(new Circle(5));
        shapes.add(new Rectangle(4, 6));
        shapes.add(new Triangle(3, 4, 3, 4, 5));
        for (Shape shape : shapes) {
            System.out.printf("%s -> Area: %.2f, Perimeter: %.2f%n",
                    shape.name(), shape.area(), shape.perimeter());
        }
    }
}Code language: Java (java)

Explanation:

  • abstract class Shape: Defines a common contract with abstract methods that every subclass must implement.
  • Math.PI * radius * radius: Calculates the area of the circle using the standard geometry formula.
  • List<Shape> shapes: Stores different subclass objects under a single supertype reference, enabling polymorphic behavior.
  • shape.area(): Calls the overridden method specific to each subclass at runtime, which is the core idea of dynamic method dispatch.

Exercise 3: BankAccount Hierarchy with Withdrawal Rules

Problem Statement: Write a Java program that creates a BankAccount base class with SavingsAccount and CheckingAccount subclasses. Each subclass should override the withdrawal method with its own rule: SavingsAccount must maintain a minimum balance of 500, while CheckingAccount allows an overdraft up to 1000.

Purpose: This exercise helps you practice overriding behavior in subclasses to implement different business rules while sharing common structure, a pattern widely used in financial and account management systems.

Given Input: A SavingsAccount with balance 1000 attempting to withdraw 700, and a CheckingAccount with balance 200 attempting to withdraw 900.

Expected Output:

Withdrawal denied. Minimum balance of 500 must be maintained.
Withdrawal successful. New balance: -700.0
💡 Hint
  • Define a protected balance field in BankAccount so subclasses can access it directly.
  • Declare withdraw(double amount) in the base class and override it in each subclass.
  • In SavingsAccount, deny the withdrawal if balance - amount falls below 500.
  • In CheckingAccount, allow the balance to go negative but not below -1000.
✅ Solution & Explanation

Solution:

class BankAccount {
    protected double balance;
    public BankAccount(double balance) {
        this.balance = balance;
    }
    public void withdraw(double amount) {
        balance -= amount;
        System.out.println("Withdrawal successful. New balance: " + balance);
    }
}
class SavingsAccount extends BankAccount {
    private static final double MIN_BALANCE = 500;
    public SavingsAccount(double balance) {
        super(balance);
    }
    @Override
    public void withdraw(double amount) {
        if (balance - amount < MIN_BALANCE) {
            System.out.println("Withdrawal denied. Minimum balance of 500 must be maintained.");
        } else {
            balance -= amount;
            System.out.println("Withdrawal successful. New balance: " + balance);
        }
    }
}
class CheckingAccount extends BankAccount {
    private static final double OVERDRAFT_LIMIT = -1000;
    public CheckingAccount(double balance) {
        super(balance);
    }
    @Override
    public void withdraw(double amount) {
        if (balance - amount < OVERDRAFT_LIMIT) {
            System.out.println("Withdrawal denied. Overdraft limit exceeded.");
        } else {
            balance -= amount;
            System.out.println("Withdrawal successful. New balance: " + balance);
        }
    }
}
public class BankAccountDemo {
    public static void main(String[] args) {
        SavingsAccount savings = new SavingsAccount(1000);
        savings.withdraw(700);
        CheckingAccount checking = new CheckingAccount(200);
        checking.withdraw(900);
    }
}Code language: Java (java)

Explanation:

  • protected double balance: Allows subclasses to read and modify the balance directly while still hiding it from outside the hierarchy.
  • @Override: Marks that each subclass provides its own version of withdraw(), replacing the base class behavior.
  • balance - amount < MIN_BALANCE: Enforces the savings account rule by rejecting withdrawals that would breach the minimum balance.
  • OVERDRAFT_LIMIT: Lets the checking account balance go negative but only up to a fixed limit, modeling a real overdraft facility.

Exercise 4: Polymorphism with Employee, Manager, and Developer

Problem Statement: Write a Java program that defines an Employee base class with a calculateBonus() method. Create Manager and Developer subclasses that override this method to calculate bonuses differently: managers get 20% of their salary, developers get 10% plus a fixed amount of 5000.

Purpose: This exercise helps you practice runtime polymorphism, where the same method call produces different results depending on the actual object type, a pattern common in payroll, pricing, and reporting systems.

Given Input: A Manager named "Asha" with salary 80000 and a Developer named "Rohan" with salary 60000.

Expected Output:

Asha (Manager) bonus: 16000.0
Rohan (Developer) bonus: 11000.0
💡 Hint
  • Store name and salary as protected fields in Employee.
  • Declare double calculateBonus() in Employee and override it in each subclass.
  • Loop through a List[Employee] and call calculateBonus() on each element.
✅ Solution & Explanation

Solution:

import java.util.ArrayList;
import java.util.List;
class Employee {
    protected String name;
    protected double salary;
    public Employee(String name, double salary) {
        this.name = name;
        this.salary = salary;
    }
    double calculateBonus() {
        return 0;
    }
    String role() {
        return "Employee";
    }
}
class Manager extends Employee {
    public Manager(String name, double salary) {
        super(name, salary);
    }
    @Override
    double calculateBonus() {
        return salary * 0.20;
    }
    @Override
    String role() {
        return "Manager";
    }
}
class Developer extends Employee {
    public Developer(String name, double salary) {
        super(name, salary);
    }
    @Override
    double calculateBonus() {
        return salary * 0.10 + 5000;
    }
    @Override
    String role() {
        return "Developer";
    }
}
public class PolymorphismDemo {
    public static void main(String[] args) {
        List<Employee> employees = new ArrayList<>();
        employees.add(new Manager("Asha", 80000));
        employees.add(new Developer("Rohan", 60000));
        for (Employee emp : employees) {
            System.out.println(emp.name + " (" + emp.role() + ") bonus: " + emp.calculateBonus());
        }
    }
}Code language: Java (java)

Explanation:

  • calculateBonus(): Declared in the base class as a placeholder so every subclass provides its own logic.
  • salary * 0.20: Computes the manager's bonus as a flat 20% of salary.
  • salary * 0.10 + 5000: Computes the developer's bonus as 10% of salary plus a fixed component.
  • emp.calculateBonus(): Even though emp is declared as type Employee, Java calls the correct overridden method based on the actual object, which is runtime polymorphism.

Exercise 5: Singleton Pattern for a Logger Class

Problem Statement: Write a Java program that implements the Singleton design pattern for a Logger class, ensuring only one instance of the class can ever be created, and use it to log a few messages.

Purpose: This exercise helps you practice the Singleton pattern, which is used when exactly one shared instance of a class should exist across an application, such as a logger, configuration manager, or connection pool.

Given Input: Two calls to Logger.getInstance() followed by a comparison and two log messages.

Expected Output:

Both references point to the same instance: true
LOG: Application started
LOG: Processing request
💡 Hint
  • Make the constructor private so no other class can instantiate Logger directly.
  • Keep a private static field holding the single instance.
  • Provide a public static getInstance() method that creates the instance only if it does not already exist.
✅ Solution & Explanation

Solution:

class Logger {
    private static Logger instance;

    private Logger() {
    }

    public static Logger getInstance() {
        if (instance == null) {
            instance = new Logger();
        }
        return instance;
    }

    public void log(String message) {
        System.out.println("LOG: " + message);
    }
}

public class SingletonDemo {
    public static void main(String[] args) {
        Logger logger1 = Logger.getInstance();
        Logger logger2 = Logger.getInstance();

        System.out.println("Both references point to the same instance: " + (logger1 == logger2));

        logger1.log("Application started");
        logger2.log("Processing request");
    }
}Code language: Java (java)

Explanation:

  • private Logger(): Prevents any class outside Logger from creating new instances with the new keyword.
  • private static Logger instance: Holds the single shared instance for the entire application.
  • getInstance(): Creates the instance only the first time it is called and returns the same object on every subsequent call.
  • logger1 == logger2: Confirms both variables reference the exact same object in memory, proving the Singleton behavior.

Exercise 6: Group Students by Grade Using Map

Problem Statement: Write a Java program that groups a list of Student objects by their grade using a Map<String, List<Student>>.

Purpose: This exercise helps you practice organizing objects into categories using a map of lists, a common pattern when grouping records by department, category, or status in real applications.

Given Input: Students "Amit" (A), "Neha" (B), "Ravi" (A), "Kiran" (C), "Simran" (B).

Expected Output:

A: [Amit, Ravi]
B: [Neha, Simran]
C: [Kiran]
💡 Hint
  • Use Map.computeIfAbsent(grade, k -> new ArrayList<>()) to create the list only when needed.
  • Add each student's name to the list mapped to their grade.
  • Use a TreeMap instead of HashMap if you want the grades printed in sorted order.
✅ Solution & Explanation

Solution:

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
class Student {
    String name;
    String grade;
    public Student(String name, String grade) {
        this.name = name;
        this.grade = grade;
    }
}
public class GroupByGrade {
    public static void main(String[] args) {
        List<Student> students = new ArrayList<>();
        students.add(new Student("Amit", "A"));
        students.add(new Student("Neha", "B"));
        students.add(new Student("Ravi", "A"));
        students.add(new Student("Kiran", "C"));
        students.add(new Student("Simran", "B"));
        Map<String, List<String>> grouped = new TreeMap<>();
        for (Student student : students) {
            grouped.computeIfAbsent(student.grade, k -> new ArrayList<>()).add(student.name);
        }
        for (Map.Entry<String, List<String>> entry : grouped.entrySet()) {
            System.out.println(entry.getKey() + ": " + entry.getValue());
        }
    }
}Code language: Java (java)

Explanation:

  • TreeMap<String, List<String>>: Stores grades as keys and lists of student names as values, sorted naturally by key.
  • computeIfAbsent(student.grade, k -> new ArrayList<>()): Creates a new list for a grade only the first time it is encountered, then returns the existing list on later calls.
  • .add(student.name): Appends the student's name to the list associated with their grade.
  • entrySet(): Iterates over the map's key-value pairs to print each grade with its list of students.

Exercise 7: Remove Duplicate Employees Using Custom equals and hashCode

Problem Statement: Write a Java program that removes duplicate Employee objects from a List<Employee> by defining a custom equals() and hashCode() based on the employee ID.

Purpose: This exercise helps you practice overriding equals() and hashCode() so that collections like HashSet can correctly identify duplicate objects based on business meaning rather than reference identity.

Given Input: Employees with IDs 101, 102, 101, 103, 102.

Expected Output: Unique employee IDs: [101, 102, 103]

💡 Hint
  • Override equals() to compare the id field between two Employee objects.
  • Override hashCode() using Objects.hash(id) so it stays consistent with equals().
  • Add all employees to a LinkedHashSet to remove duplicates while preserving insertion order.
✅ Solution & Explanation

Solution:

import java.util.ArrayList;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Objects;
import java.util.Set;
class Employee {
    int id;
    public Employee(int id) {
        this.id = id;
    }
    @Override
    public boolean equals(Object obj) {
        if (this == obj) return true;
        if (!(obj instanceof Employee)) return false;
        Employee other = (Employee) obj;
        return id == other.id;
    }
    @Override
    public int hashCode() {
        return Objects.hash(id);
    }
    @Override
    public String toString() {
        return String.valueOf(id);
    }
}
public class RemoveDuplicateEmployees {
    public static void main(String[] args) {
        List<Employee> employees = new ArrayList<>();
        employees.add(new Employee(101));
        employees.add(new Employee(102));
        employees.add(new Employee(101));
        employees.add(new Employee(103));
        employees.add(new Employee(102));
        Set<Employee> uniqueEmployees = new LinkedHashSet<>(employees);
        System.out.println("Unique employee IDs: " + uniqueEmployees);
    }
}Code language: Java (java)

Explanation:

  • equals(): Defines two Employee objects as equal when their id values match, regardless of whether they are the same object reference.
  • hashCode(): Ensures objects considered equal produce the same hash code, which is required for correct behavior in hash-based collections.
  • new LinkedHashSet<>(employees): Removes duplicates automatically while keeping the original insertion order of unique elements.

Exercise 8: Sort Products by Multiple Fields Using Comparator

Problem Statement: Write a Java program that sorts a List<Product> first by price in ascending order, and then by name alphabetically when prices are equal, using Comparator.comparing().thenComparing().

Purpose: This exercise helps you practice chaining comparators to sort objects by multiple criteria, a common requirement when displaying product listings, leaderboards, or search results.

Given Input: Products "Mouse" (500), "Keyboard" (500), "Monitor" (8000), "Speaker" (1500).

Expected Output:

Keyboard - 500.0
Mouse - 500.0
Speaker - 1500.0
Monitor - 8000.0
💡 Hint
  • Use Comparator.comparing(Product::getPrice) as the primary sort key.
  • Chain .thenComparing(Product::getName) to break ties alphabetically.
  • Pass the combined comparator to list.sort() or Collections.sort().
✅ Solution & Explanation

Solution:

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
class Product {
    private String name;
    private double price;
    public Product(String name, double price) {
        this.name = name;
        this.price = price;
    }
    public String getName() {
        return name;
    }
    public double getPrice() {
        return price;
    }
}
public class SortProducts {
    public static void main(String[] args) {
        List<Product> products = new ArrayList<>();
        products.add(new Product("Mouse", 500));
        products.add(new Product("Keyboard", 500));
        products.add(new Product("Monitor", 8000));
        products.add(new Product("Speaker", 1500));
        products.sort(Comparator.comparing(Product::getPrice)
                .thenComparing(Product::getName));
        for (Product product : products) {
            System.out.println(product.getName() + " - " + product.getPrice());
        }
    }
}Code language: Java (java)

Explanation:

  • Comparator.comparing(Product::getPrice): Builds a comparator that sorts products by price using a method reference.
  • .thenComparing(Product::getName): Adds a secondary sort key that only takes effect when two products have the same price.
  • products.sort(...): Applies the combined comparator directly to the list, sorting it in place.

Exercise 9: Find the Top 3 Highest Scoring Students

Problem Statement: Write a Java program that finds the top 3 highest scoring students from a Map<String, Integer> where the key is the student's name and the value is their score.

Purpose: This exercise helps you practice sorting map entries by value, a technique often used for building leaderboards, rankings, and top-performer reports.

Given Input: {"Amit": 85, "Neha": 92, "Ravi": 78, "Kiran": 95, "Simran": 88}

Expected Output:

Kiran: 95
Neha: 92
Simran: 88
💡 Hint
  • Convert the map's entry set into a List<Map.Entry<String, Integer>>.
  • Sort the list in descending order using Comparator.comparing(Map.Entry::getValue).reversed().
  • Use a stream with .limit(3) to take only the top three entries.
✅ Solution & Explanation

Solution:

import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
public class TopScorers {
    public static void main(String[] args) {
        Map<String, Integer> scores = new HashMap<>();
        scores.put("Amit", 85);
        scores.put("Neha", 92);
        scores.put("Ravi", 78);
        scores.put("Kiran", 95);
        scores.put("Simran", 88);
        List<Map.Entry<String, Integer>> topThree = scores.entrySet()
                .stream()
                .sorted(Map.Entry.<String, Integer>comparingByValue().reversed())
                .limit(3)
                .collect(Collectors.toList());
        for (Map.Entry<String, Integer> entry : topThree) {
            System.out.println(entry.getKey() + ": " + entry.getValue());
        }
    }
}Code language: Java (java)

Explanation:

  • scores.entrySet().stream(): Converts the map into a stream of key-value entries that can be sorted and filtered.
  • Map.Entry.comparingByValue().reversed(): Sorts entries by their score value in descending order.
  • .limit(3): Restricts the stream to only the first three entries after sorting, giving the top scorers.
  • collect(Collectors.toList()): Gathers the resulting stream elements back into a list for iteration.

Exercise 10: Merge Two HashMaps, Summing Values for Duplicate Keys

Problem Statement: Write a Java program that merges two HashMap<String, Integer> objects into one, summing the values whenever the same key appears in both maps.

Purpose: This exercise helps you practice combining data from multiple sources into a single map, a pattern frequently used when merging sales totals, inventory counts, or vote tallies from different batches.

Given Input: map1 = {"apple": 10, "banana": 5, "mango": 8} and map2 = {"banana": 7, "mango": 2, "grape": 4}

Expected Output:

apple: 10
banana: 12
mango: 10
grape: 4
💡 Hint
  • Start by copying all entries from the first map into the result map.
  • Use map.merge(key, value, Integer::sum) to add values from the second map, combining automatically when a key already exists.
  • Loop through the second map's entry set to apply merge() for each key.
✅ Solution & Explanation

Solution:

import java.util.HashMap;
import java.util.Map;
public class MergeMaps {
    public static void main(String[] args) {
        Map<String, Integer> map1 = new HashMap<>();
        map1.put("apple", 10);
        map1.put("banana", 5);
        map1.put("mango", 8);
        Map<String, Integer> map2 = new HashMap<>();
        map2.put("banana", 7);
        map2.put("mango", 2);
        map2.put("grape", 4);
        Map<String, Integer> merged = new HashMap<>(map1);
        for (Map.Entry<String, Integer> entry : map2.entrySet()) {
            merged.merge(entry.getKey(), entry.getValue(), Integer::sum);
        }
        for (Map.Entry<String, Integer> entry : merged.entrySet()) {
            System.out.println(entry.getKey() + ": " + entry.getValue());
        }
    }
}Code language: Java (java)

Explanation:

  • new HashMap<>(map1): Creates a new map pre-populated with all entries from the first map so the original is not modified.
  • merged.merge(entry.getKey(), entry.getValue(), Integer::sum): Adds the key from the second map if absent, or sums the values together if the key already exists.
  • Integer::sum: Supplies the merge function that combines two integer values by adding them.

Exercise 11: Word Frequency Counter Using HashMap

Problem Statement: Write a Java program that counts how many times each word appears in a given sentence using a HashMap<String, Integer>.

Purpose: This exercise helps you practice tokenizing text and using a map to tally occurrences, a technique widely used in text analysis, search indexing, and log processing.

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

Expected Output:

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 sentence.split(" ").
  • Use map.merge(word, 1, Integer::sum) to increment the count for each word.
  • Use a LinkedHashMap if you want the words printed in the order they first appear.
✅ Solution & Explanation

Solution:

import java.util.LinkedHashMap;
import java.util.Map;
public class WordFrequencyCounter {
    public static void main(String[] args) {
        String sentence = "the quick brown fox jumps over the lazy dog the fox runs";
        String[] words = sentence.split(" ");
        Map<String, Integer> frequency = new LinkedHashMap<>();
        for (String word : words) {
            frequency.merge(word, 1, Integer::sum);
        }
        for (Map.Entry<String, Integer> entry : frequency.entrySet()) {
            System.out.println(entry.getKey() + ": " + entry.getValue());
        }
    }
}Code language: Java (java)

Explanation:

  • sentence.split(" "): Breaks the sentence into an array of individual words using a space as the delimiter.
  • frequency.merge(word, 1, Integer::sum): Inserts the word with a count of 1 if it is not already present, or adds 1 to the existing count if it is.
  • LinkedHashMap: Preserves the insertion order of words so the output matches the order they first appeared in the sentence.

Exercise 12: Convert a List of Strings to a Map Using Streams

Problem Statement: Write a Java program that converts a List<String> into a Map<String, Integer> where each string is mapped to its length, using the Stream API.

Purpose: This exercise helps you practice using Collectors.toMap() to transform a list into a map in a single expression, a pattern commonly used when converting raw data into lookup structures.

Given Input: List.of("apple", "fig", "banana", "kiwi")

Expected Output:

apple: 5
fig: 3
banana: 6
kiwi: 4
💡 Hint
  • Call .stream() on the list and use Collectors.toMap(...).
  • Use s -> s as the key mapper and String::length as the value mapper.
  • Pass LinkedHashMap::new as the map supplier argument to preserve insertion order.
✅ Solution & Explanation

Solution:

import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
public class ListToMap {
    public static void main(String[] args) {
        List<String> words = List.of("apple", "fig", "banana", "kiwi");
        Map<String, Integer> lengthMap = words.stream()
                .collect(Collectors.toMap(
                        word -> word,
                        String::length,
                        (a, b) -> a,
                        LinkedHashMap::new
                ));
        for (Map.Entry<String, Integer> entry : lengthMap.entrySet()) {
            System.out.println(entry.getKey() + ": " + entry.getValue());
        }
    }
}Code language: Java (java)

Explanation:

  • Collectors.toMap(word -> word, String::length, ...): Builds a map where each string becomes a key and its length becomes the value.
  • (a, b) -> a: Supplies a merge function to resolve duplicate keys, keeping the first value if the same string appears twice.
  • LinkedHashMap::new: Tells the collector to use a LinkedHashMap implementation so the original list order is preserved in the resulting map.

Exercise 13: Check If Two Strings Are Anagrams

Problem Statement: Write a Java program that checks whether two given strings are anagrams of each other, meaning they contain the same characters in a different order.

Purpose: This exercise helps you practice character-level manipulation and sorting, skills that are useful in text comparison, puzzle solving, and data validation tasks.

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

Expected Output: listen and silent are anagrams: true

💡 Hint
  • Remove any spaces and convert both strings to lowercase before comparing.
  • Convert each string to a char array using toCharArray() and sort it with Arrays.sort().
  • Compare the two sorted arrays using Arrays.equals().
✅ Solution & Explanation

Solution:

import java.util.Arrays;

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

        System.out.println(str1 + " and " + str2 + " are anagrams: " + isAnagram(str1, str2));
    }

    static boolean isAnagram(String str1, String str2) {
        String clean1 = str1.replaceAll("\\s", "").toLowerCase();
        String clean2 = str2.replaceAll("\\s", "").toLowerCase();

        if (clean1.length() != clean2.length()) {
            return false;
        }

        char[] chars1 = clean1.toCharArray();
        char[] chars2 = clean2.toCharArray();

        Arrays.sort(chars1);
        Arrays.sort(chars2);

        return Arrays.equals(chars1, chars2);
    }
}Code language: Java (java)

Explanation:

  • replaceAll("\\s", "").toLowerCase(): Normalizes both strings by removing whitespace and ignoring case differences before comparison.
  • toCharArray(): Converts each string into an array of individual characters so they can be sorted.
  • Arrays.sort(chars1): Arranges the characters alphabetically, so two anagrams end up with identical sorted arrays.
  • Arrays.equals(chars1, chars2): Compares the two sorted arrays element by element to confirm they are identical.

Exercise 14: Basic Caesar Cipher for Encoding and Decoding a String

Problem Statement: Write a Java program that implements a basic Caesar cipher, shifting each letter of a string by a given number of positions to encode it, and reversing the shift to decode it back.

Purpose: This exercise helps you practice character arithmetic and wraparound logic using the ASCII value of characters, foundational skills for basic cryptography and text transformation tasks.

Given Input: text = "Hello World", shift = 3

Expected Output:

Encoded: Khoor Zruog
Decoded: Hello World
💡 Hint
  • Process each character with charAt() and check if it is a letter using Character.isLetter().
  • Use a base of 'A' or 'a' depending on the character's case to keep the shifted letter within the alphabet.
  • Apply the modulo operator % 26 to wrap around after 'z' or 'Z'.
  • To decode, shift in the opposite direction using the same logic with a negative shift.
✅ Solution & Explanation

Solution:

public class CaesarCipher {
    public static void main(String[] args) {
        String text = "Hello World";
        int shift = 3;

        String encoded = shiftText(text, shift);
        String decoded = shiftText(encoded, -shift);

        System.out.println("Encoded: " + encoded);
        System.out.println("Decoded: " + decoded);
    }

    static String shiftText(String text, int shift) {
        StringBuilder result = new StringBuilder();

        for (char ch : text.toCharArray()) {
            if (Character.isUpperCase(ch)) {
                char shifted = (char) ((ch - 'A' + shift + 26) % 26 + 'A');
                result.append(shifted);
            } else if (Character.isLowerCase(ch)) {
                char shifted = (char) ((ch - 'a' + shift + 26) % 26 + 'a');
                result.append(shifted);
            } else {
                result.append(ch);
            }
        }

        return result.toString();
    }
}Code language: Java (java)

Explanation:

  • ch - 'A' + shift + 26: Converts the letter to a zero-based index, applies the shift, and adds 26 to keep the value positive before taking the modulo.
  • % 26: Wraps the shifted index around the alphabet so it stays within the range of 26 letters.
  • + 'A': Converts the wrapped index back into the corresponding character.
  • shiftText(encoded, -shift): Reuses the same method with a negative shift value to reverse the encoding and recover the original text.

Exercise 15: Find the Longest Palindromic Substring

Problem Statement: Write a Java program that finds the longest palindromic substring within a given string.

Purpose: This exercise helps you practice the expand-around-center technique for palindrome detection, a common pattern in string processing and technical interview problems.

Given Input: text = "babad"

Expected Output: Longest palindromic substring: bab

💡 Hint
  • For each index in the string, try expanding outward from that single character (odd-length palindrome).
  • Also try expanding outward from each pair of adjacent characters (even-length palindrome).
  • Keep track of the longest palindrome found so far as you check every center.
✅ Solution & Explanation

Solution:

public class LongestPalindrome {
    public static void main(String[] args) {
        String text = "babad";
        System.out.println("Longest palindromic substring: " + longestPalindrome(text));
    }
    static String longestPalindrome(String text) {
        if (text == null || text.length() < 1) {
            return "";
        }
        String longest = "";
        for (int i = 0; i < text.length(); i++) {
            String odd = expandFromCenter(text, i, i);
            String even = expandFromCenter(text, i, i + 1);
            if (odd.length() > longest.length()) {
                longest = odd;
            }
            if (even.length() > longest.length()) {
                longest = even;
            }
        }
        return longest;
    }
    static String expandFromCenter(String text, int left, int right) {
        while (left >= 0 && right < text.length() && text.charAt(left) == text.charAt(right)) {
            left--;
            right++;
        }
        return text.substring(left + 1, right);
    }
}Code language: Java (java)

Explanation:

  • expandFromCenter(text, i, i): Checks for the longest odd-length palindrome centered on a single character at index i.
  • expandFromCenter(text, i, i + 1): Checks for the longest even-length palindrome centered between two adjacent characters.
  • left-- , right++: Expands outward from the center as long as the characters on both sides match, growing the palindrome.
  • text.substring(left + 1, right): Extracts the palindrome once the expansion stops, adjusting for the final out-of-bounds step.

Exercise 16: Count Vowels, Consonants, and Digits in a Mixed String

Problem Statement: Write a Java program that counts the number of vowels, consonants, and digits present in a given mixed string.

Purpose: This exercise helps you practice character classification using conditional checks, a skill useful in input validation, text analysis, and parsing tasks.

Given Input: text = "Hello World 123"

Expected Output:

Vowels: 3
Consonants: 7
Digits: 3
💡 Hint
  • Loop through each character and convert it to lowercase for uniform comparison.
  • Check if the character is one of a, e, i, o, u to count vowels.
  • Use Character.isLetter() for consonants and Character.isDigit() for digits.
✅ Solution & Explanation

Solution:

public class CharacterCounter {
    public static void main(String[] args) {
        String text = "Hello World 123";

        int vowels = 0, consonants = 0, digits = 0;

        for (char ch : text.toCharArray()) {
            char lower = Character.toLowerCase(ch);

            if (Character.isLetter(lower)) {
                if (lower == 'a' || lower == 'e' || lower == 'i' || lower == 'o' || lower == 'u') {
                    vowels++;
                } else {
                    consonants++;
                }
            } else if (Character.isDigit(lower)) {
                digits++;
            }
        }

        System.out.println("Vowels: " + vowels);
        System.out.println("Consonants: " + consonants);
        System.out.println("Digits: " + digits);
    }
}Code language: Java (java)

Explanation:

  • Character.toLowerCase(ch): Normalizes each character so vowel comparisons do not need to check both cases separately.
  • Character.isLetter(lower): Confirms the character is alphabetic before classifying it as a vowel or consonant.
  • lower == 'a' || lower == 'e' ...: Checks the character against the five vowels to decide whether it counts as a vowel or a consonant.
  • Character.isDigit(lower): Identifies numeric characters separately from letters to update the digit count.

Exercise 17: Reverse Each Word in a Sentence While Keeping Word Order

Problem Statement: Write a Java program that reverses each word in a sentence individually while keeping the overall order of the words unchanged.

Purpose: This exercise helps you practice splitting a sentence into tokens and applying a transformation to each one, a pattern useful in text formatting and simple obfuscation tasks.

Given Input: sentence = "Java is fun to learn"

Expected Output: avaJ si nuf ot nrael

💡 Hint
  • Split the sentence into words using split(" ").
  • Use a StringBuilder to reverse each individual word with reverse().
  • Join the reversed words back together with a single space in between.
✅ Solution & Explanation

Solution:

public class ReverseEachWord {
    public static void main(String[] args) {
        String sentence = "Java is fun to learn";
        System.out.println(reverseEachWord(sentence));
    }
    static String reverseEachWord(String sentence) {
        String[] words = sentence.split(" ");
        StringBuilder result = new StringBuilder();
        for (int i = 0; i < words.length; i++) {
            String reversedWord = new StringBuilder(words[i]).reverse().toString();
            result.append(reversedWord);
            if (i < words.length - 1) {
                result.append(" ");
            }
        }
        return result.toString();
    }
}Code language: Java (java)

Explanation:

  • sentence.split(" "): Breaks the sentence into an array of individual words while preserving their order.
  • new StringBuilder(words[i]).reverse(): Reverses the characters within a single word without affecting the other words.
  • result.append(" "): Adds a single space between reversed words, skipping it after the last word to avoid trailing whitespace.

Exercise 18: Build a Custom InsufficientFundsException

Problem Statement: Write a Java program that defines a custom checked exception InsufficientFundsException and throws it from a withdrawal method whenever the withdrawal amount exceeds the available balance.

Purpose: This exercise helps you practice creating custom exception classes to represent domain-specific error conditions, which makes error handling clearer and more meaningful than relying on generic exceptions.

Given Input: An account with balance 1000 attempting to withdraw 1500.

Expected Output: Error: Insufficient funds. Attempted to withdraw 1500.0 but balance is 1000.0

💡 Hint
  • Create InsufficientFundsException as a subclass of Exception with a constructor that accepts a message.
  • In the withdrawal method, declare throws InsufficientFundsException in the method signature.
  • Throw the exception with a descriptive message when the amount exceeds the balance.
  • Wrap the call in a try-catch block in main and print the exception's message.
✅ Solution & Explanation

Solution:

class InsufficientFundsException extends Exception {
    public InsufficientFundsException(String message) {
        super(message);
    }
}

class Account {
    private double balance;

    public Account(double balance) {
        this.balance = balance;
    }

    public void withdraw(double amount) throws InsufficientFundsException {
        if (amount > balance) {
            throw new InsufficientFundsException(
                    "Insufficient funds. Attempted to withdraw " + amount + " but balance is " + balance);
        }
        balance -= amount;
    }
}

public class InsufficientFundsDemo {
    public static void main(String[] args) {
        Account account = new Account(1000);

        try {
            account.withdraw(1500);
        } catch (InsufficientFundsException e) {
            System.out.println("Error: " + e.getMessage());
        }
    }
}Code language: Java (java)

Explanation:

  • class InsufficientFundsException extends Exception: Defines a checked exception so callers of withdraw() are required to either catch it or declare it.
  • throws InsufficientFundsException: Declares that the method may throw this exception, making the contract explicit to any caller.
  • throw new InsufficientFundsException(...): Raises the exception with a message describing exactly why the withdrawal failed.
  • catch (InsufficientFundsException e): Catches the specific exception type and retrieves its message using getMessage().

Exercise 19: Chain of Custom Exceptions Using getCause

Problem Statement: Write a Java program that demonstrates exception chaining by catching a low-level custom exception and wrapping it inside a higher-level custom exception, then retrieving the original cause using getCause().

Purpose: This exercise helps you practice preserving the root cause of an error while translating it into a more meaningful exception type, which is common in layered applications where low-level errors need to be reported in higher-level terms.

Given Input: A DataAccessException thrown internally, caught and wrapped inside a ServiceException.

Expected Output:

Service error: Unable to process request
Caused by: Database connection failed
💡 Hint
  • Create two custom exceptions: DataAccessException and ServiceException, both extending Exception.
  • Give ServiceException a constructor that accepts both a message and a Throwable cause, passing them to super(message, cause).
  • Catch the DataAccessException and wrap it in a new ServiceException, passing the caught exception as the cause.
  • Use e.getCause().getMessage() to access the original exception's message.
✅ Solution & Explanation

Solution:

class DataAccessException extends Exception {
    public DataAccessException(String message) {
        super(message);
    }
}

class ServiceException extends Exception {
    public ServiceException(String message, Throwable cause) {
        super(message, cause);
    }
}

public class ExceptionChainingDemo {
    public static void main(String[] args) {
        try {
            processRequest();
        } catch (ServiceException e) {
            System.out.println("Service error: " + e.getMessage());
            System.out.println("Caused by: " + e.getCause().getMessage());
        }
    }

    static void processRequest() throws ServiceException {
        try {
            accessDatabase();
        } catch (DataAccessException e) {
            throw new ServiceException("Unable to process request", e);
        }
    }

    static void accessDatabase() throws DataAccessException {
        throw new DataAccessException("Database connection failed");
    }
}Code language: Java (java)

Explanation:

  • super(message, cause): Passes both the new message and the original exception to the Exception superclass, linking them together.
  • throw new ServiceException("Unable to process request", e): Wraps the low-level DataAccessException inside a higher-level ServiceException without losing the original error.
  • e.getCause(): Retrieves the original exception that triggered the current one, allowing the root cause to be inspected or logged.

Exercise 20: Validate User Input and Throw Multiple Custom Exceptions

Problem Statement: Write a Java program that validates a user's age and email input, throwing an InvalidAgeException if the age is out of range and an InvalidEmailException if the email format is incorrect.

Purpose: This exercise helps you practice defining multiple custom exception types for different validation failures, a pattern used extensively in form validation and API request handling.

Given Input: age = 15, email = "user@example.com", followed by age = 25, email = "invalid-email".

Expected Output:

Validation failed: Age must be between 18 and 60. Got: 15
Validation failed: Invalid email format: invalid-email
💡 Hint
  • Create InvalidAgeException and InvalidEmailException as separate subclasses of Exception.
  • In the validation method, check the age range first and throw InvalidAgeException if it fails.
  • Use a simple regex like email.matches("^[A-Za-z0-9+_.-]+@[A-Za-z0-9.-]+$") to validate the email format.
  • Catch both exception types separately using multiple catch blocks or a multi-catch clause.
✅ Solution & Explanation

Solution:

class InvalidAgeException extends Exception {
    public InvalidAgeException(String message) {
        super(message);
    }
}
class InvalidEmailException extends Exception {
    public InvalidEmailException(String message) {
        super(message);
    }
}
public class InputValidationDemo {
    public static void main(String[] args) {
        validateAndPrint(15, "user@example.com");
        validateAndPrint(25, "invalid-email");
    }
    static void validateAndPrint(int age, String email) {
        try {
            validate(age, email);
            System.out.println("Validation passed for age " + age + " and email " + email);
        } catch (InvalidAgeException | InvalidEmailException e) {
            System.out.println("Validation failed: " + e.getMessage());
        }
    }
    static void validate(int age, String email) throws InvalidAgeException, InvalidEmailException {
        if (age < 18 || age > 60) {
            throw new InvalidAgeException("Age must be between 18 and 60. Got: " + age);
        }
        if (!email.matches("^[A-Za-z0-9+_.-]+@[A-Za-z0-9.-]+$")) {
            throw new InvalidEmailException("Invalid email format: " + email);
        }
    }
}Code language: Java (java)

Explanation:

  • throws InvalidAgeException, InvalidEmailException: Declares that the method may throw either of the two custom exceptions depending on which validation fails.
  • if (age < 18 || age > 60): Checks the age boundary first, so an invalid age is reported before the email is even checked.
  • email.matches(...): Applies a regular expression to confirm the email follows a basic valid format.
  • catch (InvalidAgeException | InvalidEmailException e): Uses a multi-catch block to handle both exception types with shared logic, since both simply need their message printed.

Exercise 21: Use Try-With-Resources to Safely Read a File

Problem Statement: Write a Java program that uses try-with-resources to safely read the contents of a text file line by line, and handle any IOException that may occur.

Purpose: This exercise helps you practice safe resource management, where try-with-resources automatically closes the file reader even if an exception occurs, which prevents resource leaks in file and stream handling code.

Given Input: A text file notes.txt containing three lines: "First line", "Second line", "Third line".

Expected Output:

First line
Second line
Third line
💡 Hint
  • Declare the BufferedReader inside the parentheses of the try statement so it closes automatically.
  • Use reader.readLine() in a loop until it returns null.
  • Catch IOException to handle cases where the file does not exist or cannot be read.
✅ Solution & Explanation

Solution:

import java.io.BufferedReader;
import java.io.FileWriter;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;

public class TryWithResourcesDemo {
    public static void main(String[] args) {
        String fileName = "notes.txt";
        createSampleFile(fileName);
        readFile(fileName);
    }

    static void createSampleFile(String fileName) {
        try (FileWriter writer = new FileWriter(fileName)) {
            writer.write("First line" + System.lineSeparator());
            writer.write("Second line" + System.lineSeparator());
            writer.write("Third line" + System.lineSeparator());
        } catch (IOException e) {
            System.out.println("Error creating file: " + e.getMessage());
        }
    }

    static void readFile(String fileName) {
        try (BufferedReader reader = Files.newBufferedReader(Paths.get(fileName))) {
            String line;
            while ((line = reader.readLine()) != null) {
                System.out.println(line);
            }
        } catch (IOException e) {
            System.out.println("Error reading file: " + e.getMessage());
        }
    }
}Code language: Java (java)

Explanation:

  • try (BufferedReader reader = ...): Opens the file reader inside the try-with-resources block so it is automatically closed once the block finishes, even if an exception is thrown.
  • reader.readLine(): Reads one line at a time from the file, returning null when the end of the file is reached.
  • catch (IOException e): Handles errors such as a missing file or a permissions issue without crashing the program.

Exercise 22: Generic Stack Class with Push, Pop, and Peek

Problem Statement: Write a Java program that implements a generic Stack<T> class supporting push, pop, and peek operations that work with any object type.

Purpose: This exercise helps you practice writing generic classes that work with any data type while maintaining compile-time type safety, a foundational concept used throughout the Java Collections Framework.

Given Input: Push 10, 20, 30 onto an integer stack, then peek and pop.

Expected Output:

Top element: 30
Popped: 30
Top element after pop: 20
💡 Hint
  • Use a List<T> such as ArrayList<T> internally to store the stack elements.
  • push() should add to the end of the list, and pop()/peek() should operate on the last index.
  • Throw a RuntimeException or a custom exception when pop() or peek() is called on an empty stack.
✅ Solution & Explanation

Solution:

import java.util.ArrayList;
import java.util.EmptyStackException;
import java.util.List;
class Stack<T> {
    private List<T> elements = new ArrayList<>();
    public void push(T item) {
        elements.add(item);
    }
    public T pop() {
        if (elements.isEmpty()) {
            throw new EmptyStackException();
        }
        return elements.remove(elements.size() - 1);
    }
    public T peek() {
        if (elements.isEmpty()) {
            throw new EmptyStackException();
        }
        return elements.get(elements.size() - 1);
    }
    public boolean isEmpty() {
        return elements.isEmpty();
    }
}
public class GenericStackDemo {
    public static void main(String[] args) {
        Stack<Integer> stack = new Stack<>();
        stack.push(10);
        stack.push(20);
        stack.push(30);
        System.out.println("Top element: " + stack.peek());
        System.out.println("Popped: " + stack.pop());
        System.out.println("Top element after pop: " + stack.peek());
    }
}Code language: Java (java)

Explanation:

  • class Stack<T>: Declares a generic type parameter T so the same class can store integers, strings, or any other object type.
  • elements.remove(elements.size() - 1): Removes and returns the last element in the list, which represents the top of the stack.
  • elements.get(elements.size() - 1): Retrieves the top element without removing it, implementing the peek operation.
  • Stack<Integer> stack = new Stack<>(): Creates a stack specifically for integers, with the compiler enforcing type safety at every method call.

Exercise 23: Generic Method to Find the Maximum Element in an Array

Problem Statement: Write a Java program with a generic method that finds and returns the maximum element in an array of any type that implements Comparable.

Purpose: This exercise helps you practice bounded type parameters, which restrict a generic type to only those classes that support comparison, a pattern used throughout sorting and searching utilities.

Given Input: Integer[] numbers = {45, 12, 89, 33, 67} and String[] words = {"banana", "apple", "cherry"}

Expected Output:

Maximum number: 89
Maximum word: cherry
💡 Hint
  • Declare the method as static <T extends Comparable<T>> T findMax(T[] array).
  • Start by assuming the first element is the maximum, then compare it against the rest.
  • Use compareTo() to compare each element with the current maximum.
✅ Solution & Explanation

Solution:

public class GenericMaxFinder {
    public static void main(String[] args) {
        Integer[] numbers = {45, 12, 89, 33, 67};
        String[] words = {"banana", "apple", "cherry"};
        System.out.println("Maximum number: " + findMax(numbers));
        System.out.println("Maximum word: " + findMax(words));
    }
    static <T extends Comparable<T>> T findMax(T[] array) {
        T max = array[0];
        for (T element : array) {
            if (element.compareTo(max) > 0) {
                max = element;
            }
        }
        return max;
    }
}Code language: Java (java)

Explanation:

  • <T extends Comparable<T>>: Restricts the generic type to classes that implement Comparable, guaranteeing that compareTo() is available.
  • T max = array[0]: Initializes the maximum with the first element so the loop only needs to check the remaining elements.
  • element.compareTo(max) > 0: Compares each element to the current maximum, updating it whenever a larger value is found.
  • findMax(numbers) and findMax(words): Demonstrates that the same method works for both integers and strings because both types implement Comparable.

Exercise 24: Generic Pair Class with Getters and Custom toString

Problem Statement: Write a Java program that implements a generic Pair<K, V> class to hold two related values of possibly different types, along with getter methods and a custom toString() implementation.

Purpose: This exercise helps you practice working with multiple generic type parameters in a single class, a pattern commonly used for representing key-value associations, coordinates, and result tuples.

Given Input: A pair with key "age" and value 28.

Expected Output: Pair{key=age, value=28}

💡 Hint
  • Declare the class as Pair<K, V> with two private fields, key of type K and value of type V.
  • Provide a constructor that accepts both values and simple getters for each field.
  • Override toString() to format the output as Pair{key=..., value=...}.
✅ Solution & Explanation

Solution:

class Pair<K, V> {
    private K key;
    private V value;
    public Pair(K key, V value) {
        this.key = key;
        this.value = value;
    }
    public K getKey() {
        return key;
    }
    public V getValue() {
        return value;
    }
    @Override
    public String toString() {
        return "Pair{key=" + key + ", value=" + value + "}";
    }
}
public class GenericPairDemo {
    public static void main(String[] args) {
        Pair<String, Integer> pair = new Pair<>("age", 28);
        System.out.println(pair);
    }
}Code language: Java (java)

Explanation:

  • class Pair<K, V>: Declares two independent type parameters so the key and value can be of different types.
  • getKey() and getValue(): Expose the private fields through controlled read-only access, following encapsulation principles.
  • toString(): Provides a readable string representation so printing the object directly shows both the key and value clearly.
  • Pair<String, Integer>: Instantiates the generic class with a String key and an Integer value, showing how the two type parameters can differ.

Exercise 25: Read a CSV File and Parse It into a List of Employee Objects

Problem Statement: Write a Java program that reads a CSV file containing employee records and parses each line into an Employee object, storing the results in a List<Employee>.

Purpose: This exercise helps you practice reading structured text data and mapping it into domain objects, a common requirement when importing data from spreadsheets or external systems.

Given Input: A CSV file employees.csv containing:

101,Amit,50000
102,Neha,62000
103,Ravi,48000

Expected Output:

Employee{id=101, name=Amit, salary=50000.0}
Employee{id=102, name=Neha, salary=62000.0}
Employee{id=103, name=Ravi, salary=48000.0}
💡 Hint
  • Read the file line by line using BufferedReader inside try-with-resources.
  • Split each line using line.split(",") to get the individual fields.
  • Convert the id and salary fields from String to int and double using Integer.parseInt() and Double.parseDouble().
  • Create a new Employee object for each line and add it to the list.
✅ Solution & Explanation

Solution:

import java.io.BufferedReader;
import java.io.FileWriter;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
class Employee {
    int id;
    String name;
    double salary;
    public Employee(int id, String name, double salary) {
        this.id = id;
        this.name = name;
        this.salary = salary;
    }
    @Override
    public String toString() {
        return "Employee{id=" + id + ", name=" + name + ", salary=" + salary + "}";
    }
}
public class CsvToEmployeeList {
    public static void main(String[] args) throws IOException {
        String fileName = "employees.csv";
        createSampleCsv(fileName);
        List<Employee> employees = readEmployeesFromCsv(fileName);
        for (Employee emp : employees) {
            System.out.println(emp);
        }
    }
    static void createSampleCsv(String fileName) throws IOException {
        try (FileWriter writer = new FileWriter(fileName)) {
            writer.write("101,Amit,50000" + System.lineSeparator());
            writer.write("102,Neha,62000" + System.lineSeparator());
            writer.write("103,Ravi,48000" + System.lineSeparator());
        }
    }
    static List<Employee> readEmployeesFromCsv(String fileName) throws IOException {
        List<Employee> employees = new ArrayList<>();
        try (BufferedReader reader = Files.newBufferedReader(Paths.get(fileName))) {
            String line;
            while ((line = reader.readLine()) != null) {
                String[] fields = line.split(",");
                int id = Integer.parseInt(fields[0]);
                String name = fields[1];
                double salary = Double.parseDouble(fields[2]);
                employees.add(new Employee(id, name, salary));
            }
        }
        return employees;
    }
}Code language: Java (java)

Explanation:

  • line.split(","): Splits each CSV line into an array of fields using the comma as a delimiter.
  • Integer.parseInt(fields[0]): Converts the id field from text to a numeric type so it matches the Employee constructor's expected type.
  • employees.add(new Employee(...)): Creates a new object for each parsed line and appends it to the growing list of employees.
  • readEmployeesFromCsv(fileName): Encapsulates the entire parsing logic in a reusable method that returns a ready-to-use list of objects.

Exercise 26: Count Lines, Words, and Characters in a Text File

Problem Statement: Write a Java program that reads a text file and counts the total number of lines, words, and characters it contains.

Purpose: This exercise helps you practice combining file reading with text analysis, a technique commonly used in tools like word counters, log analyzers, and document statistics utilities.

Given Input: A text file sample.txt containing two lines: "Java is powerful" and "Java is popular".

Expected Output:

Lines: 2
Words: 6
Characters: 32
💡 Hint
  • Read the file line by line and increment a line counter for each line read.
  • Split each line on whitespace using line.split("\\s+") to count words.
  • Add line.length() to a running character total, including the newline character for each line.
✅ Solution & Explanation

Solution:

import java.io.BufferedReader;
import java.io.FileWriter;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;

public class FileStatsCounter {
    public static void main(String[] args) throws IOException {
        String fileName = "sample.txt";
        createSampleFile(fileName);
        countFileStats(fileName);
    }

    static void createSampleFile(String fileName) throws IOException {
        try (FileWriter writer = new FileWriter(fileName)) {
            writer.write("Java is powerful" + System.lineSeparator());
            writer.write("Java is popular" + System.lineSeparator());
        }
    }

    static void countFileStats(String fileName) throws IOException {
        int lines = 0, words = 0, characters = 0;

        try (BufferedReader reader = Files.newBufferedReader(Paths.get(fileName))) {
            String line;
            while ((line = reader.readLine()) != null) {
                lines++;
                words += line.split("\\s+").length;
                characters += line.length() + 1;
            }
        }

        System.out.println("Lines: " + lines);
        System.out.println("Words: " + words);
        System.out.println("Characters: " + characters);
    }
}Code language: Java (java)

Explanation:

  • lines++: Increments the line counter every time a new line is successfully read from the file.
  • line.split("\\s+").length: Splits the line on one or more whitespace characters and counts the resulting number of words.
  • line.length() + 1: Adds the character count of the line plus one for the newline character that readLine() strips off.

Exercise 27: Two Threads Print Even and Odd Numbers Alternately

Problem Statement: Write a Java program that uses two threads, one printing even numbers and the other printing odd numbers, so that the numbers appear alternately from 1 to 10 in the correct order using synchronization.

Purpose: This exercise helps you practice thread coordination using wait() and notify(), which are fundamental tools for controlling execution order between threads that share state.

Given Input: A shared counter starting at 1, printed up to 10 by two alternating threads.

Expected Output:

Odd: 1
Even: 2
Odd: 3
Even: 4
Odd: 5
Even: 6
Odd: 7
Even: 8
Odd: 9
Even: 10
💡 Hint
  • Use a shared object with a synchronized method that both threads call in a loop.
  • Inside the synchronized block, check if it is the correct thread's turn based on whether the counter is even or odd.
  • If it is not the thread's turn, call wait(); after printing, increment the counter and call notify() to wake the other thread.
✅ Solution & Explanation

Solution:

class NumberPrinter {
    private int counter = 1;
    private final int max = 10;
    public synchronized void printOdd() throws InterruptedException {
        while (counter <= max) {
            while (counter % 2 == 0) {
                wait();
            }
            System.out.println("Odd: " + counter);
            counter++;
            notify();
        }
    }
    public synchronized void printEven() throws InterruptedException {
        while (counter <= max) {
            while (counter % 2 != 0) {
                wait();
            }
            System.out.println("Even: " + counter);
            counter++;
            notify();
        }
    }
}
public class EvenOddThreadDemo {
    public static void main(String[] args) {
        NumberPrinter printer = new NumberPrinter();
        Thread oddThread = new Thread(() -> {
            try {
                printer.printOdd();
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
            }
        });
        Thread evenThread = new Thread(() -> {
            try {
                printer.printEven();
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
            }
        });
        oddThread.start();
        evenThread.start();
    }
}Code language: Java (java)

Explanation:

  • synchronized void printOdd(): Ensures only one thread at a time can execute this method on the shared NumberPrinter instance.
  • wait(): Pauses the current thread and releases the lock whenever it is not that thread's turn to print, allowing the other thread to proceed.
  • notify(): Wakes up the other waiting thread after the counter is updated, signaling that it is now its turn.
  • counter % 2 == 0: Determines whose turn it is by checking whether the shared counter is currently even or odd.

Exercise 28: Producer-Consumer Problem Using BlockingQueue

Problem Statement: Write a Java program that implements the producer-consumer problem, where a producer thread generates items and a consumer thread processes them, using a BlockingQueue to coordinate between them.

Purpose: This exercise helps you practice using BlockingQueue to safely hand off data between threads without manually managing wait() and notify(), a pattern common in task queues and streaming pipelines.

Given Input: A producer generating items 1 through 5, consumed one at a time by a consumer thread.

Expected Output:

Produced: 1
Consumed: 1
Produced: 2
Consumed: 2
Produced: 3
Consumed: 3
Produced: 4
Consumed: 4
Produced: 5
Consumed: 5
💡 Hint
  • Use an ArrayBlockingQueue<Integer> with a small fixed capacity, such as 1 or 2, shared between the producer and consumer.
  • In the producer thread, call queue.put(item), which blocks automatically if the queue is full.
  • In the consumer thread, call queue.take(), which blocks automatically if the queue is empty.
  • Use Thread.join() in main to wait for both threads to finish before the program exits.
✅ Solution & Explanation

Solution:

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
public class ProducerConsumerDemo {
    public static void main(String[] args) throws InterruptedException {
        BlockingQueue<Integer> queue = new ArrayBlockingQueue<>(2);
        Thread producer = new Thread(() -> {
            try {
                for (int i = 1; i <= 5; i++) {
                    queue.put(i);
                    System.out.println("Produced: " + i);
                }
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
            }
        });
        Thread consumer = new Thread(() -> {
            try {
                for (int i = 1; i <= 5; i++) {
                    int item = queue.take();
                    System.out.println("Consumed: " + item);
                }
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
            }
        });
        producer.start();
        consumer.start();
        producer.join();
        consumer.join();
    }
}Code language: Java (java)

Explanation:

  • ArrayBlockingQueue<Integer>(2): Creates a thread-safe queue with a fixed capacity that automatically handles blocking when full or empty.
  • queue.put(i): Adds an item to the queue, pausing the producer thread automatically if the queue is already full.
  • queue.take(): Removes and returns an item from the queue, pausing the consumer thread automatically if the queue is empty.
  • producer.join() and consumer.join(): Makes the main thread wait for both threads to complete before the program terminates.

Exercise 29: Use ExecutorService to Run Tasks and Collect Results with Future

Problem Statement: Write a Java program that uses an ExecutorService to run 5 tasks concurrently, where each task calculates the square of a number, and collects the results using Future.

Purpose: This exercise helps you practice the higher-level concurrency API in Java, which manages thread creation and lifecycle for you, a pattern used extensively in server applications and parallel processing tasks.

Given Input: Numbers 1 through 5, each squared by a separate task.

Expected Output:

Square of 1 = 1
Square of 2 = 4
Square of 3 = 9
Square of 4 = 16
Square of 5 = 25
💡 Hint
  • Create an ExecutorService using Executors.newFixedThreadPool(5).
  • Submit each task as a Callable<Integer> using executor.submit(), and store the returned Future<Integer> objects in a list.
  • Call future.get() on each Future to retrieve the result once the task completes.
  • Call executor.shutdown() after all tasks are submitted to release the thread pool's resources.
✅ Solution & Explanation

Solution:

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
public class ExecutorServiceDemo {
    public static void main(String[] args) throws InterruptedException, ExecutionException {
        ExecutorService executor = Executors.newFixedThreadPool(5);
        List<Future<Integer>> futures = new ArrayList<>();
        for (int i = 1; i <= 5; i++) {
            int number = i;
            Callable<Integer> task = () -> number * number;
            futures.add(executor.submit(task));
        }
        for (int i = 0; i < futures.size(); i++) {
            int result = futures.get(i).get();
            System.out.println("Square of " + (i + 1) + " = " + result);
        }
        executor.shutdown();
    }
}Code language: Java (java)

Explanation:

  • Executors.newFixedThreadPool(5): Creates a pool of 5 reusable threads capable of running submitted tasks concurrently.
  • Callable<Integer> task = () -> number * number: Defines a task that returns a computed value, unlike Runnable which does not return anything.
  • executor.submit(task): Schedules the task for execution and immediately returns a Future representing its eventual result.
  • futures.get(i).get(): Blocks until the corresponding task completes and then retrieves its computed result.
  • executor.shutdown(): Signals the executor to stop accepting new tasks and release its thread pool once existing tasks finish.

Exercise 30: Find the Average Salary per Department Using Streams

Problem Statement: Write a Java program that, given a List<Employee> where each employee has a department and a salary, uses the Stream API to calculate the average salary per department.

Purpose: This exercise helps you practice grouping and aggregating data using Collectors.groupingBy() combined with a downstream collector, a pattern frequently used in reporting and analytics code.

Given Input: Employees "Amit" (Engineering, 60000), "Neha" (Engineering, 70000), "Ravi" (Sales, 50000), "Kiran" (Sales, 55000), "Simran" (HR, 45000).

Expected Output:

Engineering: 65000.0
HR: 45000.0
Sales: 52500.0
💡 Hint
  • Use employees.stream().collect(Collectors.groupingBy(...)) with the department as the grouping key.
  • Pass Collectors.averagingDouble(Employee::getSalary) as the downstream collector to compute the average within each group.
  • Use a TreeMap::new map supplier if you want departments printed in alphabetical order.
✅ Solution & Explanation

Solution:

import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import java.util.stream.Collectors;
class Employee {
    String name;
    String department;
    double salary;
    public Employee(String name, String department, double salary) {
        this.name = name;
        this.department = department;
        this.salary = salary;
    }
    public double getSalary() {
        return salary;
    }
    public String getDepartment() {
        return department;
    }
}
public class AverageSalaryByDepartment {
    public static void main(String[] args) {
        List<Employee> employees = List.of(
                new Employee("Amit", "Engineering", 60000),
                new Employee("Neha", "Engineering", 70000),
                new Employee("Ravi", "Sales", 50000),
                new Employee("Kiran", "Sales", 55000),
                new Employee("Simran", "HR", 45000)
        );
        Map<String, Double> averageByDepartment = employees.stream()
                .collect(Collectors.groupingBy(
                        Employee::getDepartment,
                        TreeMap::new,
                        Collectors.averagingDouble(Employee::getSalary)
                ));
        for (Map.Entry<String, Double> entry : averageByDepartment.entrySet()) {
            System.out.println(entry.getKey() + ": " + entry.getValue());
        }
    }
}Code language: Java (java)

Explanation:

  • Collectors.groupingBy(Employee::getDepartment, ...): Groups employees into buckets keyed by their department name.
  • Collectors.averagingDouble(Employee::getSalary): Acts as a downstream collector that computes the average salary within each department group.
  • TreeMap::new: Tells the grouping collector to store results in a TreeMap so departments appear in alphabetical order.
  • averageByDepartment.entrySet(): Iterates over the resulting map to print each department alongside its computed average salary.

Exercise 31: Rotate a 2D Matrix by 90 Degrees In Place

Problem Statement: Write a Java program that rotates a square 2D matrix by 90 degrees clockwise without using an extra matrix.

Purpose: This exercise helps you practice in-place matrix manipulation using transposition and reversal, a technique commonly used in image processing and grid-based puzzle problems.

Given Input: {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}}

Expected Output:

7 4 1
8 5 2
9 6 3
💡 Hint
  • First transpose the matrix by swapping matrix[i][j] with matrix[j][i] for all i < j.
  • Then reverse each row of the transposed matrix to complete the 90 degree clockwise rotation.
  • Both steps can be done in place without allocating a second matrix.
✅ Solution & Explanation

Solution:

public class RotateMatrix {
    public static void main(String[] args) {
        int[][] matrix = {
                {1, 2, 3},
                {4, 5, 6},
                {7, 8, 9}
        };
        rotate(matrix);
        printMatrix(matrix);
    }
    static void rotate(int[][] matrix) {
        int n = matrix.length;
        for (int i = 0; i < n; i++) {
            for (int j = i + 1; j < n; j++) {
                int temp = matrix[i][j];
                matrix[i][j] = matrix[j][i];
                matrix[j][i] = temp;
            }
        }
        for (int[] row : matrix) {
            int left = 0, right = row.length - 1;
            while (left < right) {
                int temp = row[left];
                row[left] = row[right];
                row[right] = temp;
                left++;
                right--;
            }
        }
    }
    static void printMatrix(int[][] matrix) {
        for (int[] row : matrix) {
            StringBuilder line = new StringBuilder();
            for (int value : row) {
                line.append(value).append(" ");
            }
            System.out.println(line.toString().trim());
        }
    }
}Code language: Java (java)

Explanation:

  • matrix[i][j] = matrix[j][i]: Swaps elements across the main diagonal to transpose the matrix, converting rows into columns.
  • left++, right--: Reverses each row from both ends toward the center, which combined with the transpose completes a 90 degree clockwise rotation.
  • j = i + 1: Starts the inner loop after the diagonal to avoid swapping each pair of elements twice.

Exercise 32: Find the Transpose of a Matrix

Problem Statement: Write a Java program that computes the transpose of a given matrix, converting its rows into columns.

Purpose: This exercise helps you practice iterating over a 2D array with nested loops and understanding index relationships, which is foundational for many linear algebra and grid transformation tasks.

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

Expected Output:

1 4
2 5
3 6
💡 Hint
  • Since the input is not necessarily square, create a new matrix with swapped dimensions: columns x rows.
  • Assign transposed[j][i] = original[i][j] for every element.
  • Print the resulting matrix row by row.
✅ Solution & Explanation

Solution:

public class MatrixTranspose {
    public static void main(String[] args) {
        int[][] matrix = {
                {1, 2, 3},
                {4, 5, 6}
        };
        int[][] transposed = transpose(matrix);
        printMatrix(transposed);
    }
    static int[][] transpose(int[][] matrix) {
        int rows = matrix.length;
        int cols = matrix[0].length;
        int[][] result = new int[cols][rows];
        for (int i = 0; i < rows; i++) {
            for (int j = 0; j < cols; j++) {
                result[j][i] = matrix[i][j];
            }
        }
        return result;
    }
    static void printMatrix(int[][] matrix) {
        for (int[] row : matrix) {
            StringBuilder line = new StringBuilder();
            for (int value : row) {
                line.append(value).append(" ");
            }
            System.out.println(line.toString().trim());
        }
    }
}Code language: Java (java)

Explanation:

  • new int[cols][rows]: Allocates the result matrix with dimensions swapped compared to the original, since a transpose flips rows and columns.
  • result[j][i] = matrix[i][j]: Places each original element into its mirrored position in the new matrix, effectively swapping its row and column indices.
  • transpose(matrix): Returns a brand new matrix rather than modifying the original, which is necessary here since the dimensions can differ for non-square matrices.

Exercise 33: Binary Search Returning the Insertion Point If Not Found

Problem Statement: Write a Java program that performs binary search on a sorted array and returns the index of the target if found, or the index where it should be inserted to keep the array sorted if not found.

Purpose: This exercise helps you practice the binary search algorithm along with correctly tracking pointer boundaries, a pattern used in searching, sorted insertion, and range queries.

Given Input: numbers = {1, 3, 5, 7, 9}, target = 6

Expected Output: Insertion point: 3

💡 Hint
  • Use the standard binary search structure with low and high pointers.
  • If the target is found, return its index directly.
  • If the loop ends without finding the target, low will already point to the correct insertion index.
✅ Solution & Explanation

Solution:

public class BinarySearchInsertionPoint {
    public static void main(String[] args) {
        int[] numbers = {1, 3, 5, 7, 9};
        int target = 6;
        int result = searchInsertPosition(numbers, target);
        System.out.println("Insertion point: " + result);
    }
    static int searchInsertPosition(int[] numbers, int target) {
        int low = 0, high = numbers.length - 1;
        while (low <= high) {
            int mid = low + (high - low) / 2;
            if (numbers[mid] == target) {
                return mid;
            } else if (numbers[mid] < target) {
                low = mid + 1;
            } else {
                high = mid - 1;
            }
        }
        return low;
    }
}Code language: Java (java)

Explanation:

  • low + (high - low) / 2: Calculates the middle index safely, avoiding potential overflow that could occur with (low + high) / 2 on very large arrays.
  • numbers[mid] < target: Narrows the search to the right half by moving low past the midpoint when the target is larger.
  • return low: Once the loop ends without a match, low has converged to the exact position where the target would need to be inserted to preserve sorted order.

Exercise 34: Find All Pairs in an Array That Sum to a Target Value

Problem Statement: Write a Java program that finds all unique pairs of numbers in an array whose sum equals a given target value.

Purpose: This exercise helps you practice using a HashSet to solve the classic two-sum problem in a single pass, a technique frequently used in array processing and interview-style problems.

Given Input: numbers = {2, 4, 3, 5, 7, 8, -1}, target = 7

Expected Output:

(4, 3)
(-1, 8)
💡 Hint
  • Use a HashSet<Integer> to keep track of numbers already seen while iterating.
  • For each number, compute complement = target - number and check if it already exists in the set.
  • Add the current number to the set after checking, so each pair is only reported once.
✅ Solution & Explanation

Solution:

import java.util.HashSet;
import java.util.Set;
public class PairSumFinder {
    public static void main(String[] args) {
        int[] numbers = {2, 4, 3, 5, 7, 8, -1};
        int target = 7;
        findPairs(numbers, target);
    }
    static void findPairs(int[] numbers, int target) {
        Set<Integer> seen = new HashSet<>();
        for (int number : numbers) {
            int complement = target - number;
            if (seen.contains(complement)) {
                System.out.println("(" + number + ", " + complement + ")");
            }
            seen.add(number);
        }
    }
}Code language: Java (java)

Explanation:

  • Set<Integer> seen: Stores every number encountered so far, allowing constant-time lookups to check for a matching complement.
  • complement = target - number: Calculates the value that, when added to the current number, would produce the target sum.
  • seen.contains(complement): Checks whether the required complement has already appeared earlier in the array, confirming a valid pair.
  • seen.add(number): Adds the current number to the set only after the check, ensuring the same element is not paired with itself.

Exercise 35: Merge Two Sorted Arrays Without Using Extra Sort Calls

Problem Statement: Write a Java program that merges two already sorted arrays into a single sorted array using the standard merge technique, without calling any sort method.

Purpose: This exercise helps you practice the merge step used in merge sort, where two sorted sequences are combined in linear time by comparing elements from both sides.

Given Input: array1 = {1, 3, 5, 7}, array2 = {2, 4, 6, 8, 10}

Expected Output: Merged array: [1, 2, 3, 4, 5, 6, 7, 8, 10]

💡 Hint
  • Use three pointers: one for each input array and one for the position in the result array.
  • Compare the elements at the two array pointers and copy the smaller one into the result, advancing that pointer.
  • After the main loop, copy any remaining elements from whichever array still has leftover items.
✅ Solution & Explanation

Solution:

import java.util.Arrays;
public class MergeSortedArrays {
    public static void main(String[] args) {
        int[] array1 = {1, 3, 5, 7};
        int[] array2 = {2, 4, 6, 8, 10};
        int[] merged = merge(array1, array2);
        System.out.println("Merged array: " + Arrays.toString(merged));
    }
    static int[] merge(int[] array1, int[] array2) {
        int[] result = new int[array1.length + array2.length];
        int i = 0, j = 0, k = 0;
        while (i < array1.length && j < array2.length) {
            if (array1[i] <= array2[j]) {
                result[k++] = array1[i++];
            } else {
                result[k++] = array2[j++];
            }
        }
        while (i < array1.length) {
            result[k++] = array1[i++];
        }
        while (j < array2.length) {
            result[k++] = array2[j++];
        }
        return result;
    }
}Code language: Java (java)

Explanation:

  • array1[i] <= array2[j]: Compares the current elements of both arrays and copies the smaller one into the result, keeping the merged array sorted.
  • result[k++]: Writes into the next open slot of the result array and advances the result pointer in the same expression.
  • Trailing while loops: Copy over any remaining elements once one array is fully consumed, since the leftover elements in the other array are already sorted.

Exercise 36: Tower of Hanoi, Printing Each Move

Problem Statement: Write a Java program that solves the Tower of Hanoi puzzle for a given number of disks using recursion, printing each move made from one rod to another.

Purpose: This exercise helps you practice classic recursive problem decomposition, where a large problem is solved by reducing it to smaller subproblems of the same shape, a pattern foundational to algorithm design.

Given Input: disks = 3, moving from rod A to rod C using rod B as auxiliary.

Expected Output:

Move disk 1 from A to C
Move disk 2 from A to B
Move disk 1 from C to B
Move disk 3 from A to C
Move disk 1 from B to A
Move disk 2 from B to C
Move disk 1 from A to C
💡 Hint
  • The base case is a single disk, which can be moved directly from the source to the destination.
  • For n disks, first move n - 1 disks from source to auxiliary, then move the largest disk to the destination, then move the n - 1 disks from auxiliary to destination.
  • Each recursive call swaps the roles of source, auxiliary, and destination accordingly.
✅ Solution & Explanation

Solution:

public class TowerOfHanoi {
    public static void main(String[] args) {
        int disks = 3;
        solve(disks, 'A', 'C', 'B');
    }

    static void solve(int disks, char source, char destination, char auxiliary) {
        if (disks == 1) {
            System.out.println("Move disk 1 from " + source + " to " + destination);
            return;
        }

        solve(disks - 1, source, auxiliary, destination);
        System.out.println("Move disk " + disks + " from " + source + " to " + destination);
        solve(disks - 1, auxiliary, destination, source);
    }
}Code language: Java (java)

Explanation:

  • if (disks == 1): Handles the base case where a single disk can be moved directly without any further recursion.
  • solve(disks - 1, source, auxiliary, destination): Recursively moves the top n - 1 disks out of the way onto the auxiliary rod before the largest disk can move.
  • solve(disks - 1, auxiliary, destination, source): Recursively moves the same n - 1 disks from the auxiliary rod onto the destination rod, completing the puzzle for this level.

Exercise 37: Recursive Method to Calculate the GCD of Two Numbers

Problem Statement: Write a Java program that calculates the greatest common divisor of two numbers using a recursive implementation of the Euclidean algorithm.

Purpose: This exercise helps you practice writing a simple, well-defined recursive function with a clear base case, a good introduction to recursion before tackling more complex recursive problems.

Given Input: a = 48, b = 18

Expected Output: GCD of 48 and 18 is: 6

💡 Hint
  • The base case is when the second number becomes 0, at which point the first number is the GCD.
  • Otherwise, recursively call the method with b and a % b.
✅ Solution & Explanation

Solution:

public class RecursiveGCD {
    public static void main(String[] args) {
        int a = 48, b = 18;
        System.out.println("GCD of " + a + " and " + b + " is: " + gcd(a, b));
    }

    static int gcd(int a, int b) {
        if (b == 0) {
            return a;
        }
        return gcd(b, a % b);
    }
}Code language: Java (java)

Explanation:

  • if (b == 0): Defines the base case of the recursion, since the GCD of any number and 0 is that number itself.
  • gcd(b, a % b): Applies the Euclidean algorithm's core rule that gcd(a, b) equals gcd(b, a % b), shrinking the problem each time until the base case is reached.

Exercise 38: Generate All Permutations of a String Using Recursion

Problem Statement: Write a Java program that generates and prints all possible permutations of a given string using recursion.

Purpose: This exercise helps you practice backtracking, where a solution is built incrementally and characters are swapped and restored at each recursive step, a pattern used in combinatorial problems.

Given Input: text = "abc"

Expected Output:

abc
acb
bac
bca
cba
cab
💡 Hint
  • Convert the string to a character array to make swapping easier.
  • Use a recursive method that fixes one character at the current position and permutes the rest.
  • After each recursive call, swap the characters back to restore the original order before trying the next swap (backtracking).
✅ Solution & Explanation

Solution:

public class StringPermutations {
    public static void main(String[] args) {
        String text = "abc";
        char[] chars = text.toCharArray();
        permute(chars, 0);
    }
    static void permute(char[] chars, int start) {
        if (start == chars.length - 1) {
            System.out.println(new String(chars));
            return;
        }
        for (int i = start; i < chars.length; i++) {
            swap(chars, start, i);
            permute(chars, start + 1);
            swap(chars, start, i);
        }
    }
    static void swap(char[] chars, int i, int j) {
        char temp = chars[i];
        chars[i] = chars[j];
        chars[j] = temp;
    }
}Code language: Java (java)

Explanation:

  • if (start == chars.length - 1): Recognizes the base case where all positions are fixed, meaning a complete permutation has been formed and can be printed.
  • swap(chars, start, i): Places a different character at the current position before recursing, exploring a new branch of permutations.
  • Second swap(chars, start, i): Reverts the swap after the recursive call returns, restoring the array so the next iteration starts from the original arrangement, which is the essence of backtracking.

Exercise 39: Solve the N-Queens Problem for a Given Board Size

Problem Statement: Write a Java program that solves the N-Queens problem for a given board size, printing one valid arrangement where no two queens attack each other.

Purpose: This exercise helps you practice backtracking with constraint checking, where each placement is validated against previous choices before continuing, a pattern widely used in constraint satisfaction problems.

Given Input: n = 4

Expected Output:

. Q . .
. . . Q
Q . . .
. . Q .
💡 Hint
  • Use a 1D array where the index represents the row and the value represents the column of the queen in that row.
  • For each row, try placing a queen in every column and check if it conflicts with previously placed queens.
  • A conflict occurs when two queens share a column, or when the absolute difference in columns equals the absolute difference in rows (diagonal attack).
  • Stop and print the board as soon as one complete valid solution is found.
✅ Solution & Explanation

Solution:

public class NQueens {
    public static void main(String[] args) {
        int n = 4;
        int[] positions = new int[n];
        solve(positions, 0, n);
    }
    static boolean solve(int[] positions, int row, int n) {
        if (row == n) {
            printBoard(positions, n);
            return true;
        }
        for (int col = 0; col < n; col++) {
            if (isSafe(positions, row, col)) {
                positions[row] = col;
                if (solve(positions, row + 1, n)) {
                    return true;
                }
            }
        }
        return false;
    }
    static boolean isSafe(int[] positions, int row, int col) {
        for (int i = 0; i < row; i++) {
            if (positions[i] == col || Math.abs(positions[i] - col) == Math.abs(i - row)) {
                return false;
            }
        }
        return true;
    }
    static void printBoard(int[] positions, int n) {
        for (int row = 0; row < n; row++) {
            StringBuilder line = new StringBuilder();
            for (int col = 0; col < n; col++) {
                line.append(positions[row] == col ? "Q" : ".").append(" ");
            }
            System.out.println(line.toString().trim());
        }
    }
}Code language: Java (java)

Explanation:

  • isSafe(positions, row, col): Checks the current column against every previously placed queen for both column conflicts and diagonal conflicts before allowing a placement.
  • Math.abs(positions[i] - col) == Math.abs(i - row): Detects diagonal attacks by comparing the row and column differences between two queens.
  • if (row == n): Recognizes that once every row has a valid queen placement, a complete solution has been found and can be printed.
  • solve(positions, row + 1, n): Recurses into the next row only after a safe placement, and backtracks automatically by trying the next column if no valid placement leads to a full solution.

Exercise 40: Flatten a Nested List Structure Using Recursion

Problem Statement: Write a Java program that flattens a nested list structure, where a list may contain integers or other nested lists, into a single flat List<Integer> using recursion.

Purpose: This exercise helps you practice recursively processing arbitrarily nested data structures, a pattern often needed when working with JSON-like data, trees, or hierarchical configurations.

Given Input: A nested list representing [1, [2, 3, [4, 5]], 6, [7, [8, 9]]]

Expected Output: Flattened list: [1, 2, 3, 4, 5, 6, 7, 8, 9]

💡 Hint
  • Represent the nested structure using List<Object>, where each element is either an Integer or another List<Object>.
  • For each element, check its type using instanceof.
  • If the element is a list, recursively flatten it; if it is an integer, add it directly to the result list.
✅ Solution & Explanation

Solution:

import java.util.ArrayList;
import java.util.List;
public class FlattenNestedList {
    public static void main(String[] args) {
        List<Object> nested = new ArrayList<>();
        nested.add(1);
        nested.add(List.of(2, 3, List.of(4, 5)));
        nested.add(6);
        nested.add(List.of(7, List.of(8, 9)));
        List<Integer> flat = new ArrayList<>();
        flatten(nested, flat);
        System.out.println("Flattened list: " + flat);
    }
    @SuppressWarnings("unchecked")
    static void flatten(List<Object> nested, List<Integer> result) {
        for (Object element : nested) {
            if (element instanceof List) {
                flatten((List<Object>) element, result);
            } else if (element instanceof Integer) {
                result.add((Integer) element);
            }
        }
    }
}Code language: Java (java)

Explanation:

  • element instanceof List: Detects whether the current element is itself a nested list, in which case it needs further flattening rather than being added directly.
  • flatten((List<Object>) element, result): Recursively processes the nested list, passing along the same result list so all flattened integers accumulate in one place.
  • element instanceof Integer: Identifies a plain integer, which is added directly to the flat result list without further recursion.

Exercise 41: Enum Season with a Method Returning Its Months

Problem Statement: Write a Java program that defines an enum Season with constants WINTER, SPRING, SUMMER, and FALL, and includes a method that returns the list of months belonging to each season.

Purpose: This exercise helps you practice giving behavior to enum constants by attaching fields and methods, which is far more powerful than using enums as plain constant labels.

Given Input: Season.SUMMER

Expected Output: SUMMER months: [June, July, August]

💡 Hint
  • Give each enum constant a List<String> field for its months, passed through the constructor.
  • Use List.of(...) when defining each constant to assign its specific months.
  • Add a getter method getMonths() that returns the field for the calling constant.
✅ Solution & Explanation

Solution:

import java.util.List;
enum Season {
    WINTER(List.of("December", "January", "February")),
    SPRING(List.of("March", "April", "May")),
    SUMMER(List.of("June", "July", "August")),
    FALL(List.of("September", "October", "November"));
    private final List<String> months;
    Season(List<String> months) {
        this.months = months;
    }
    public List<String> getMonths() {
        return months;
    }
}
public class SeasonDemo {
    public static void main(String[] args) {
        Season season = Season.SUMMER;
        System.out.println(season + " months: " + season.getMonths());
    }
}Code language: Java (java)

Explanation:

  • WINTER(List.of(...)): Passes a list of months to the enum constructor for each constant, associating specific data with that particular season.
  • Season(List<String> months): Defines a private constructor that runs once for each constant when the enum is initialized.
  • season.getMonths(): Retrieves the list of months tied to whichever constant the variable currently holds, here SUMMER.

Exercise 42: Enum TrafficLight with a Method to Transition to the Next State

Problem Statement: Write a Java program that defines an enum TrafficLight with constants RED, GREEN, and YELLOW, including a method next() that returns the light that should follow the current one.

Purpose: This exercise helps you practice modeling a cyclic state transition directly within an enum, a pattern useful for representing systems with a small, fixed set of well-defined states.

Given Input: Starting state RED, transitioning three times.

Expected Output:

RED -> GREEN
GREEN -> YELLOW
YELLOW -> RED
💡 Hint
  • Implement next() using a switch expression over this, returning the appropriate next constant for each case.
  • Make sure YELLOW wraps back around to RED to complete the cycle.
✅ Solution & Explanation

Solution:

enum TrafficLight {
    RED, GREEN, YELLOW;
    public TrafficLight next() {
        switch (this) {
            case RED:
                return GREEN;
            case GREEN:
                return YELLOW;
            case YELLOW:
                return RED;
            default:
                throw new IllegalStateException("Unknown state: " + this);
        }
    }
}
public class TrafficLightDemo {
    public static void main(String[] args) {
        TrafficLight current = TrafficLight.RED;
        for (int i = 0; i < 3; i++) {
            TrafficLight nextLight = current.next();
            System.out.println(current + " -> " + nextLight);
            current = nextLight;
        }
    }
}Code language: Java (java)

Explanation:

  • switch (this): Uses the enum instance itself as the switch value to decide which constant should follow it.
  • case YELLOW: return RED: Wraps the cycle back to the beginning, so the state machine keeps looping indefinitely.
  • current = nextLight: Advances the current state after each transition so the next call to next() continues correctly from the updated state.

Exercise 43: Order Processing State Machine Using Enums

Problem Statement: Write a Java program that models an order processing system using an enum OrderStatus with states PLACED, SHIPPED, and DELIVERED, and a method that validates whether a transition from one state to another is allowed.

Purpose: This exercise helps you practice enforcing valid state transitions within an enum, a pattern used in order management, workflow engines, and any system with a strict sequence of stages.

Given Input: Attempt transition PLACED -> SHIPPED, then PLACED -> DELIVERED.

Expected Output:

PLACED -> SHIPPED : allowed
PLACED -> DELIVERED : not allowed
💡 Hint
  • Give each enum constant a field holding the single valid next state, or null if it is the final state.
  • Add a method canTransitionTo(OrderStatus target) that compares the target against the stored next state.
  • Since DELIVERED has no valid next state, pass null for it in the constructor.
✅ Solution & Explanation

Solution:

enum OrderStatus {
    PLACED(null),
    SHIPPED(null),
    DELIVERED(null);

    private OrderStatus nextStatus;

    static {
        PLACED.nextStatus = SHIPPED;
        SHIPPED.nextStatus = DELIVERED;
        DELIVERED.nextStatus = null;
    }

    OrderStatus(OrderStatus nextStatus) {
        this.nextStatus = nextStatus;
    }

    public boolean canTransitionTo(OrderStatus target) {
        return nextStatus == target;
    }
}

public class OrderStateMachineDemo {
    public static void main(String[] args) {
        checkTransition(OrderStatus.PLACED, OrderStatus.SHIPPED);
        checkTransition(OrderStatus.PLACED, OrderStatus.DELIVERED);
    }

    static void checkTransition(OrderStatus from, OrderStatus to) {
        String result = from.canTransitionTo(to) ? "allowed" : "not allowed";
        System.out.println(from + " -> " + to + " : " + result);
    }
}Code language: Java (java)

Explanation:

  • Static initializer block: Assigns each constant's valid next status after all enum constants have been created, since a constant cannot reference another constant that is not yet defined inside its own constructor call.
  • canTransitionTo(OrderStatus target): Compares the requested target status against the single valid next status stored for the current state.
  • PLACED.canTransitionTo(DELIVERED): Returns false because PLACED can only transition to SHIPPED directly, enforcing the correct order sequence.

Exercise 44: Calculate Business Days Between Two LocalDate Values

Problem Statement: Write a Java program that calculates the number of business days (excluding Saturdays and Sundays) between two given LocalDate values.

Purpose: This exercise helps you practice working with the java.time API and DayOfWeek enum to filter dates based on weekday rules, a common requirement in scheduling and payroll systems.

Given Input: start = 2026-07-01, end = 2026-07-10

Expected Output: Business days: 8

💡 Hint
  • Loop from start to end inclusive using date.plusDays(1) at each step.
  • Use date.getDayOfWeek() and check it is not SATURDAY or SUNDAY.
  • Increment a counter each time the date passes the weekday check.
✅ Solution & Explanation

Solution:

import java.time.DayOfWeek;
import java.time.LocalDate;

public class BusinessDaysCalculator {
    public static void main(String[] args) {
        LocalDate start = LocalDate.of(2026, 7, 1);
        LocalDate end = LocalDate.of(2026, 7, 10);

        int businessDays = countBusinessDays(start, end);
        System.out.println("Business days: " + businessDays);
    }

    static int countBusinessDays(LocalDate start, LocalDate end) {
        int count = 0;
        LocalDate current = start;

        while (!current.isAfter(end)) {
            DayOfWeek day = current.getDayOfWeek();
            if (day != DayOfWeek.SATURDAY && day != DayOfWeek.SUNDAY) {
                count++;
            }
            current = current.plusDays(1);
        }

        return count;
    }
}Code language: Java (java)

Explanation:

  • !current.isAfter(end): Keeps the loop running until the current date passes the end date, ensuring the end date itself is included.
  • current.getDayOfWeek(): Retrieves the day of the week as a DayOfWeek enum value, which can be directly compared to SATURDAY and SUNDAY.
  • current.plusDays(1): Advances the loop one day at a time without mutating the original LocalDate, since LocalDate is immutable.

Exercise 45: Check If a Given Year Is a Leap Year Using java.time

Problem Statement: Write a Java program that checks whether a given year is a leap year using the java.time API rather than manual arithmetic.

Purpose: This exercise helps you practice relying on the built-in date and time library instead of reimplementing calendar rules manually, which reduces the chance of subtle bugs in leap year logic.

Given Input: year = 2024 and year = 2023

Expected Output:

2024 is a leap year: true
2023 is a leap year: false
💡 Hint
  • Use the static method Year.isLeap(long year) from the java.time package.
  • Alternatively, create a Year object with Year.of(year) and call isLeap() on the instance.
✅ Solution & Explanation

Solution:

import java.time.Year;

public class LeapYearChecker {
    public static void main(String[] args) {
        int[] years = {2024, 2023};

        for (int year : years) {
            System.out.println(year + " is a leap year: " + Year.isLeap(year));
        }
    }
}Code language: Java (java)

Explanation:

  • Year.isLeap(year): Calls the built-in static method that correctly applies the leap year rules, including the century exception, without any manual calculation.
  • Using java.time over manual arithmetic: Avoids common mistakes such as forgetting that years divisible by 100 are not leap years unless also divisible by 400.

Exercise 46: Age Calculator Using Period

Problem Statement: Write a Java program that calculates a person's age in years, months, and days by computing a Period between their birthdate and the current date.

Purpose: This exercise helps you practice using Period to represent a date-based amount of time, which is the correct tool for measuring elapsed calendar time rather than doing manual date subtraction.

Given Input: birthDate = 2000-03-15, current date assumed to be 2026-07-07.

Expected Output: Age: 26 years, 3 months, 23 days

💡 Hint
  • Use Period.between(birthDate, currentDate) to compute the difference.
  • Call getYears(), getMonths(), and getDays() on the resulting Period object to extract each component.
  • Use LocalDate.now() to get today's date if you want the age calculated relative to the current system date.
✅ Solution & Explanation

Solution:

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

public class AgeCalculator {
    public static void main(String[] args) {
        LocalDate birthDate = LocalDate.of(2000, 3, 15);
        LocalDate currentDate = LocalDate.of(2026, 7, 7);

        Period age = Period.between(birthDate, currentDate);

        System.out.println("Age: " + age.getYears() + " years, "
                + age.getMonths() + " months, "
                + age.getDays() + " days");
    }
}Code language: Java (java)

Explanation:

  • Period.between(birthDate, currentDate): Calculates the calendar-based difference between the two dates, correctly accounting for varying month lengths and leap years.
  • age.getYears(): Extracts just the whole years component of the period, separate from the leftover months and days.
  • age.getMonths() and age.getDays(): Extract the remaining months and days after the full years have been accounted for, giving a precise breakdown of the age.

Exercise 47: Format and Parse Dates in Multiple Locales Using DateTimeFormatter

Problem Statement: Write a Java program that formats a given date into two different locale-specific styles using DateTimeFormatter, and then parses a date string back into a LocalDate.

Purpose: This exercise helps you practice using DateTimeFormatter with locale-aware and custom patterns, a skill needed when displaying dates to users in different regions or parsing dates from external data sources.

Given Input: date = 2026-07-07

Expected Output:

US format: Jul 7, 2026
UK format: 07-Jul-2026
Parsed date: 2026-12-25
💡 Hint
  • Use DateTimeFormatter.ofPattern("MMM d, yyyy", Locale.US) for the US-style output.
  • Use a different pattern such as "dd-MMM-yyyy" with Locale.UK for the UK-style output.
  • Use LocalDate.parse(text, formatter) to convert a formatted string back into a LocalDate.
✅ Solution & Explanation

Solution:

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

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

        DateTimeFormatter usFormatter = DateTimeFormatter.ofPattern("MMM d, yyyy", Locale.US);
        DateTimeFormatter ukFormatter = DateTimeFormatter.ofPattern("dd-MMM-yyyy", Locale.UK);

        System.out.println("US format: " + date.format(usFormatter));
        System.out.println("UK format: " + date.format(ukFormatter));

        DateTimeFormatter parseFormatter = DateTimeFormatter.ofPattern("dd-MMM-yyyy", Locale.UK);
        LocalDate parsedDate = LocalDate.parse("25-Dec-2026", parseFormatter);
        System.out.println("Parsed date: " + parsedDate);
    }
}Code language: Java (java)

Explanation:

  • DateTimeFormatter.ofPattern("MMM d, yyyy", Locale.US): Builds a formatter using a custom pattern combined with a specific locale, which affects things like month name spelling.
  • date.format(usFormatter): Applies the formatter to convert the LocalDate object into a human-readable string in the desired style.
  • LocalDate.parse("25-Dec-2026", parseFormatter): Converts a formatted date string back into a LocalDate object using the same pattern that was used to produce that format.

Exercise 48: Validate an Email Address Using a Regular Expression

Problem Statement: Write a Java program that validates whether a given string is a properly formatted email address using a regular expression.

Purpose: This exercise helps you practice writing and applying a regular expression for a common real-world validation task, a skill needed in form validation and data cleansing.

Given Input: "user@example.com" and "invalid-email"

Expected Output:

user@example.com is valid: true
invalid-email is valid: false
💡 Hint
  • Use a pattern like "^[A-Za-z0-9+_.-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,}$" to validate the general structure.
  • Call email.matches(pattern) to test the string against the regex.
✅ Solution & Explanation

Solution:

public class EmailValidator {
    public static void main(String[] args) {
        String[] emails = {"user@example.com", "invalid-email"};

        for (String email : emails) {
            System.out.println(email + " is valid: " + isValidEmail(email));
        }
    }

    static boolean isValidEmail(String email) {
        String pattern = "^[A-Za-z0-9+_.-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,}$";
        return email.matches(pattern);
    }
}Code language: Java (java)

Explanation:

  • [A-Za-z0-9+_.-]+: Matches one or more valid characters allowed before the @ symbol in the local part of the email.
  • [A-Za-z0-9.-]+: Matches the domain name portion, allowing letters, digits, dots, and hyphens.
  • \\.[A-Za-z]{2,}$: Requires a literal dot followed by at least two letters at the end, representing the top-level domain such as com or org.
  • email.matches(pattern): Tests whether the entire string conforms to the pattern from start to end, returning true only for a fully valid match.

Exercise 49: Extract All Phone Numbers from Text Using Pattern and Matcher

Problem Statement: Write a Java program that extracts all phone numbers from a block of text using Pattern and Matcher, matching numbers in the format XXX-XXX-XXXX.

Purpose: This exercise helps you practice using Pattern and Matcher together to find all occurrences of a pattern within a larger text, a common requirement in text mining and data extraction tasks.

Given Input: "Contact us at 987-654-3210 or 123-456-7890 for support."

Expected Output:

987-654-3210
123-456-7890
💡 Hint
  • Use the pattern "\\d{3}-\\d{3}-\\d{4}" to match the phone number format.
  • Create a Matcher from Pattern.compile(...) and call matcher.find() in a loop.
  • Use matcher.group() to retrieve each matched substring.
✅ Solution & Explanation

Solution:

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class PhoneNumberExtractor {
    public static void main(String[] args) {
        String text = "Contact us at 987-654-3210 or 123-456-7890 for support.";

        Pattern pattern = Pattern.compile("\\d{3}-\\d{3}-\\d{4}");
        Matcher matcher = pattern.matcher(text);

        while (matcher.find()) {
            System.out.println(matcher.group());
        }
    }
}Code language: Java (java)

Explanation:

  • Pattern.compile("\\d{3}-\\d{3}-\\d{4}"): Compiles a regular expression matching three digits, a hyphen, three more digits, another hyphen, then four digits.
  • pattern.matcher(text): Creates a Matcher that scans the given text for occurrences of the compiled pattern.
  • matcher.find(): Advances through the text looking for the next match, returning true each time one is found until the text is exhausted.
  • matcher.group(): Returns the exact substring that matched the pattern for the current match.

Exercise 50: Password Strength Validator Using Regex

Problem Statement: Write a Java program that validates password strength using a regular expression, requiring a minimum length of 8 characters, at least one digit, and at least one special character.

Purpose: This exercise helps you practice combining multiple lookahead conditions within a single regular expression, a technique used when enforcing composite validation rules on user input.

Given Input: "Pass@123" and "weakpass"

Expected Output:

Pass@123 is strong: true
weakpass is strong: false
💡 Hint
  • Use a lookahead (?=.*\\d) to require at least one digit anywhere in the string.
  • Use a lookahead (?=.*[@#$%^&+=!]) to require at least one special character.
  • Combine both lookaheads with a length check .{8,}$ at the end of the pattern.
✅ Solution & Explanation

Solution:

public class PasswordStrengthValidator {
    public static void main(String[] args) {
        String[] passwords = {"Pass@123", "weakpass"};

        for (String password : passwords) {
            System.out.println(password + " is strong: " + isStrongPassword(password));
        }
    }

    static boolean isStrongPassword(String password) {
        String pattern = "^(?=.*\\d)(?=.*[@#$%^&+=!]).{8,}$";
        return password.matches(pattern);
    }
}Code language: Java (java)

Explanation:

  • (?=.*\\d): A lookahead that checks the string contains at least one digit somewhere, without consuming any characters itself.
  • (?=.*[@#$%^&+=!]): A second lookahead that checks for at least one special character from the specified set.
  • .{8,}$: Requires the total string length to be at least 8 characters, applied after both lookahead conditions have been satisfied.
  • password.matches(pattern): Evaluates the password against all three conditions combined into a single regular expression.

Exercise 51: Connect to a Database and Perform CRUD Operations on an Employee Table

Problem Statement: Write a Java program that connects to a MySQL database and performs Create, Read, Update, and Delete operations on an Employee table using JDBC.

Purpose: This exercise helps you practice the core JDBC workflow of obtaining a connection, creating a statement, and executing SQL commands, which is the foundation for any Java application that talks to a relational database.

Given Input: An employees table with columns id, name, and salary, in a MySQL database named company_db.

Expected Output:

Inserted employee: Amit
Employee found: Amit, salary: 50000.0
Updated salary for Amit
Deleted employee: Amit
💡 Hint
  • Use DriverManager.getConnection(url, username, password) to open the connection.
  • Use a separate Statement or PreparedStatement for each of the insert, select, update, and delete operations.
  • Wrap the connection and statements in try-with-resources so they close automatically.
  • Use executeUpdate() for insert, update, and delete, and executeQuery() for select.
✅ Solution & Explanation

Solution:

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class EmployeeCrudDemo {
    static final String URL = "jdbc:mysql://localhost:3306/company_db";
    static final String USER = "root";
    static final String PASSWORD = "your_password";

    public static void main(String[] args) {
        try (Connection connection = DriverManager.getConnection(URL, USER, PASSWORD);
             Statement statement = connection.createStatement()) {

            statement.executeUpdate(
                    "INSERT INTO employees (name, salary) VALUES ('Amit', 50000)");
            System.out.println("Inserted employee: Amit");

            ResultSet resultSet = statement.executeQuery(
                    "SELECT name, salary FROM employees WHERE name = 'Amit'");
            if (resultSet.next()) {
                System.out.println("Employee found: " + resultSet.getString("name")
                        + ", salary: " + resultSet.getDouble("salary"));
            }

            statement.executeUpdate(
                    "UPDATE employees SET salary = 55000 WHERE name = 'Amit'");
            System.out.println("Updated salary for Amit");

            statement.executeUpdate(
                    "DELETE FROM employees WHERE name = 'Amit'");
            System.out.println("Deleted employee: Amit");

        } catch (SQLException e) {
            System.out.println("Database error: " + e.getMessage());
        }
    }
}Code language: Java (java)

Explanation:

  • DriverManager.getConnection(URL, USER, PASSWORD): Opens a connection to the MySQL database using the specified URL and credentials.
  • statement.executeUpdate(...): Executes SQL statements that modify data, such as insert, update, and delete, returning the number of affected rows.
  • statement.executeQuery(...): Executes a select statement and returns a ResultSet containing the retrieved rows.
  • resultSet.next(): Advances the cursor to the next row in the result set, returning false once there are no more rows to read.

Exercise 52: Use PreparedStatement to Prevent SQL Injection

Problem Statement: Write a Java program that inserts user-supplied data into a database table using PreparedStatement instead of string concatenation, to prevent SQL injection.

Purpose: This exercise helps you practice safely parameterizing SQL queries, which is essential whenever untrusted input is used in a database operation, protecting the application from SQL injection attacks.

Given Input: A username "Neha" and an email "neha@example.com" to be inserted into a users table.

Expected Output: Rows inserted: 1

💡 Hint
  • Write the SQL with ? placeholders instead of directly embedding the variable values in the string.
  • Use connection.prepareStatement(sql) to create the PreparedStatement.
  • Set each placeholder value using setString(), matching the parameter position starting from 1.
  • Call executeUpdate() to run the insert and return the number of affected rows.
✅ Solution & Explanation

Solution:

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;

public class PreparedStatementDemo {
    static final String URL = "jdbc:mysql://localhost:3306/company_db";
    static final String USER = "root";
    static final String PASSWORD = "your_password";

    public static void main(String[] args) {
        String username = "Neha";
        String email = "neha@example.com";

        String sql = "INSERT INTO users (username, email) VALUES (?, ?)";

        try (Connection connection = DriverManager.getConnection(URL, USER, PASSWORD);
             PreparedStatement statement = connection.prepareStatement(sql)) {

            statement.setString(1, username);
            statement.setString(2, email);

            int rowsInserted = statement.executeUpdate();
            System.out.println("Rows inserted: " + rowsInserted);

        } catch (SQLException e) {
            System.out.println("Database error: " + e.getMessage());
        }
    }
}Code language: Java (java)

Explanation:

  • ? placeholders: Reserve positions in the SQL for parameter values, keeping the query structure fixed regardless of the input supplied.
  • statement.setString(1, username): Safely binds the value to the first placeholder, ensuring the driver treats it strictly as data and never as executable SQL.
  • Why this prevents injection: Because the query structure is compiled before any values are bound, a malicious string like "'; DROP TABLE users; --" is treated as plain text rather than part of the SQL command.

Exercise 53: Implement Pagination for a Large Result Set Using JDBC

Problem Statement: Write a Java program that retrieves employee records from a database in pages, using SQL LIMIT and OFFSET clauses through a PreparedStatement.

Purpose: This exercise helps you practice retrieving large result sets in manageable chunks, a technique essential for applications that display data in pages rather than loading an entire table into memory at once.

Given Input: An employees table with many rows, fetching page 2 with a page size of 5.

Expected Output: Fetching employees 6 to 10 (page 2)

💡 Hint
  • Use a SQL query with LIMIT ? OFFSET ? as placeholders for the page size and starting position.
  • Calculate the offset as (pageNumber - 1) * pageSize.
  • Set the LIMIT parameter to the page size and the OFFSET parameter to the calculated offset.
✅ Solution & Explanation

Solution:

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class PaginationDemo {
    static final String URL = "jdbc:mysql://localhost:3306/company_db";
    static final String USER = "root";
    static final String PASSWORD = "your_password";

    public static void main(String[] args) {
        int pageNumber = 2;
        int pageSize = 5;

        fetchPage(pageNumber, pageSize);
    }

    static void fetchPage(int pageNumber, int pageSize) {
        int offset = (pageNumber - 1) * pageSize;
        String sql = "SELECT id, name FROM employees ORDER BY id LIMIT ? OFFSET ?";

        System.out.println("Fetching employees " + (offset + 1) + " to "
                + (offset + pageSize) + " (page " + pageNumber + ")");

        try (Connection connection = DriverManager.getConnection(URL, USER, PASSWORD);
             PreparedStatement statement = connection.prepareStatement(sql)) {

            statement.setInt(1, pageSize);
            statement.setInt(2, offset);

            ResultSet resultSet = statement.executeQuery();
            while (resultSet.next()) {
                System.out.println(resultSet.getInt("id") + " - " + resultSet.getString("name"));
            }

        } catch (SQLException e) {
            System.out.println("Database error: " + e.getMessage());
        }
    }
}Code language: Java (java)

Explanation:

  • (pageNumber - 1) * pageSize: Calculates how many rows to skip before starting the current page, based on the requested page number.
  • LIMIT ? OFFSET ?: Restricts the query to only return pageSize rows, starting after skipping offset rows from the beginning of the ordered result.
  • ORDER BY id: Ensures a consistent row ordering across separate page requests, since pagination without a stable order can return inconsistent results.

Exercise 54: List All Methods and Fields of a Class Using Reflection

Problem Statement: Write a Java program that uses Reflection to list all declared methods and fields of a given class at runtime.

Purpose: This exercise helps you practice inspecting class metadata dynamically, a capability used in frameworks, serialization libraries, and testing tools that need to work with arbitrary classes without knowing their structure in advance.

Given Input: A class Product with fields name and price, and methods getName() and getPrice().

Expected Output:

Fields:
name
price

Methods:
getName
getPrice
💡 Hint
  • Get the Class object using Product.class or obj.getClass().
  • Use getDeclaredFields() to retrieve all fields declared directly in the class.
  • Use getDeclaredMethods() to retrieve all methods declared directly in the class.
  • Call getName() on each Field and Method object to print its name.
✅ Solution & Explanation

Solution:

import java.lang.reflect.Field;
import java.lang.reflect.Method;
class Product {
    private String name;
    private double price;
    public String getName() {
        return name;
    }
    public double getPrice() {
        return price;
    }
}
public class ReflectionInspector {
    public static void main(String[] args) {
        Class<?> clazz = Product.class;
        System.out.println("Fields:");
        for (Field field : clazz.getDeclaredFields()) {
            System.out.println(field.getName());
        }
        System.out.println();
        System.out.println("Methods:");
        for (Method method : clazz.getDeclaredMethods()) {
            System.out.println(method.getName());
        }
    }
}Code language: Java (java)

Explanation:

  • Product.class: Obtains the Class object representing the Product type, which serves as the entry point for all reflection operations on that class.
  • clazz.getDeclaredFields(): Returns an array of Field objects representing every field declared in the class, regardless of its access modifier.
  • clazz.getDeclaredMethods(): Returns an array of Method objects representing every method declared directly in the class.
  • field.getName() and method.getName(): Retrieve the string name of each field or method for display purposes.

Exercise 55: Use Reflection to Dynamically Invoke a Method by Name

Problem Statement: Write a Java program that uses Reflection to look up and invoke a method by its name at runtime, without calling it directly through normal object syntax.

Purpose: This exercise helps you practice dynamic method invocation, a capability used in plugin systems, dependency injection frameworks, and test runners that need to call methods whose names are only known at runtime.

Given Input: A Calculator object with a method add(int, int), invoked dynamically with arguments 5 and 3.

Expected Output: Result: 8

💡 Hint
  • Use clazz.getMethod("add", int.class, int.class) to look up the method by name and parameter types.
  • Call method.invoke(instance, arg1, arg2) to execute it on a specific object with the given arguments.
  • Wrap the reflective calls in a try-catch block to handle NoSuchMethodException and InvocationTargetException.
✅ Solution & Explanation

Solution:

import java.lang.reflect.Method;
class Calculator {
    public int add(int a, int b) {
        return a + b;
    }
}
public class ReflectionInvokeDemo {
    public static void main(String[] args) {
        try {
            Calculator calculator = new Calculator();
            Class<?> clazz = calculator.getClass();
            Method method = clazz.getMethod("add", int.class, int.class);
            Object result = method.invoke(calculator, 5, 3);
            System.out.println("Result: " + result);
        } catch (Exception e) {
            System.out.println("Reflection error: " + e.getMessage());
        }
    }
}Code language: Java (java)

Explanation:

  • clazz.getMethod("add", int.class, int.class): Looks up a public method named add that accepts two int parameters, returning a Method object representing it.
  • method.invoke(calculator, 5, 3): Executes the method on the given calculator instance, passing 5 and 3 as arguments, just as if calculator.add(5, 3) had been called directly.
  • catch (Exception e): Catches the checked exceptions that reflective calls can throw, such as when the method cannot be found or its invocation fails.

Exercise 56: Singly Linked List with Insert, Delete, and Reverse Operations

Problem Statement: Write a Java program that implements a singly linked list supporting insertion at the end, deletion by value, and reversing the entire list.

Purpose: This exercise helps you practice building and manipulating linked data structures by managing node references directly, a foundational skill for understanding more advanced structures like trees and graphs.

Given Input: Insert 10, 20, 30, 40, delete 20, then reverse the list.

Expected Output:

List after insertions: 10 -> 20 -> 30 -> 40 -> null
List after deleting 20: 10 -> 30 -> 40 -> null
List after reversal: 40 -> 30 -> 10 -> null
💡 Hint
  • Define a private static Node class with a value and a reference to the next node.
  • For insertion, traverse to the last node and attach the new node, or set it as head if the list is empty.
  • For deletion, track the previous node while traversing so you can bypass the node being removed.
  • For reversal, iterate through the list while redirecting each node's next pointer to the previous node.
✅ Solution & Explanation

Solution:

class LinkedList {
    private static class Node {
        int value;
        Node next;

        Node(int value) {
            this.value = value;
        }
    }

    private Node head;

    public void insert(int value) {
        Node newNode = new Node(value);
        if (head == null) {
            head = newNode;
            return;
        }
        Node current = head;
        while (current.next != null) {
            current = current.next;
        }
        current.next = newNode;
    }

    public void delete(int value) {
        if (head == null) {
            return;
        }
        if (head.value == value) {
            head = head.next;
            return;
        }
        Node current = head;
        while (current.next != null && current.next.value != value) {
            current = current.next;
        }
        if (current.next != null) {
            current.next = current.next.next;
        }
    }

    public void reverse() {
        Node previous = null;
        Node current = head;
        while (current != null) {
            Node nextNode = current.next;
            current.next = previous;
            previous = current;
            current = nextNode;
        }
        head = previous;
    }

    public void print() {
        Node current = head;
        StringBuilder result = new StringBuilder();
        while (current != null) {
            result.append(current.value).append(" -> ");
            current = current.next;
        }
        result.append("null");
        System.out.println(result);
    }
}

public class LinkedListDemo {
    public static void main(String[] args) {
        LinkedList list = new LinkedList();
        list.insert(10);
        list.insert(20);
        list.insert(30);
        list.insert(40);
        System.out.print("List after insertions: ");
        list.print();

        list.delete(20);
        System.out.print("List after deleting 20: ");
        list.print();

        list.reverse();
        System.out.print("List after reversal: ");
        list.print();
    }
}Code language: Java (java)

Explanation:

  • current.next = newNode: Attaches the new node to the end of the list after traversing to the last existing node.
  • current.next = current.next.next: Removes a node from the middle of the list by linking the previous node directly to the one after the target, bypassing it entirely.
  • current.next = previous: Reverses the direction of each node's link one at a time while walking through the list, eventually flipping the entire chain.
  • head = previous: Updates the head reference to what was previously the last node, since that node is now the start of the reversed list.

Exercise 57: Basic Binary Search Tree with Insert, Search, and In-Order Traversal

Problem Statement: Write a Java program that implements a basic binary search tree supporting insertion, searching for a value, and printing the elements using in-order traversal.

Purpose: This exercise helps you practice recursive tree operations and understand how the binary search tree property keeps elements ordered, which is foundational for many searching and indexing structures.

Given Input: Insert 50, 30, 70, 20, 40, 60, 80, then search for 40 and 90.

Expected Output:

In-order traversal: 20 30 40 50 60 70 80
Found 40: true
Found 90: false
💡 Hint
  • Define a Node class holding a value and left/right child references.
  • For insertion, recursively go left if the value is smaller, or right if it is larger, until you find an empty spot.
  • For search, follow the same left/right decision logic, returning true immediately if the value is found.
  • For in-order traversal, recursively visit the left subtree, print the node, then recursively visit the right subtree.
✅ Solution & Explanation

Solution:

class BinarySearchTree {
    private static class Node {
        int value;
        Node left, right;
        Node(int value) {
            this.value = value;
        }
    }
    private Node root;
    public void insert(int value) {
        root = insertRecursive(root, value);
    }
    private Node insertRecursive(Node node, int value) {
        if (node == null) {
            return new Node(value);
        }
        if (value < node.value) {
            node.left = insertRecursive(node.left, value);
        } else if (value > node.value) {
            node.right = insertRecursive(node.right, value);
        }
        return node;
    }
    public boolean search(int value) {
        return searchRecursive(root, value);
    }
    private boolean searchRecursive(Node node, int value) {
        if (node == null) {
            return false;
        }
        if (value == node.value) {
            return true;
        }
        return value < node.value
                ? searchRecursive(node.left, value)
                : searchRecursive(node.right, value);
    }
    public void inOrderTraversal() {
        StringBuilder result = new StringBuilder();
        inOrderRecursive(root, result);
        System.out.println("In-order traversal: " + result.toString().trim());
    }
    private void inOrderRecursive(Node node, StringBuilder result) {
        if (node == null) {
            return;
        }
        inOrderRecursive(node.left, result);
        result.append(node.value).append(" ");
        inOrderRecursive(node.right, result);
    }
}
public class BinarySearchTreeDemo {
    public static void main(String[] args) {
        BinarySearchTree tree = new BinarySearchTree();
        int[] values = {50, 30, 70, 20, 40, 60, 80};
        for (int value : values) {
            tree.insert(value);
        }
        tree.inOrderTraversal();
        System.out.println("Found 40: " + tree.search(40));
        System.out.println("Found 90: " + tree.search(90));
    }
}Code language: Java (java)

Explanation:

  • insertRecursive(node.left, value): Recursively descends into the left subtree whenever the new value is smaller than the current node, preserving the binary search tree ordering property.
  • searchRecursive(...): Uses the same left or right decision at each node to quickly narrow down where the target value would be, skipping entire subtrees that cannot contain it.
  • inOrderRecursive(...): Visits the left subtree, then the current node, then the right subtree, which naturally produces the values in ascending sorted order for a binary search tree.

Exercise 58: Implement a Queue Using Two Stacks

Problem Statement: Write a Java program that implements a queue using two stacks, supporting enqueue and dequeue operations while preserving first-in-first-out order.

Purpose: This exercise helps you practice simulating one data structure's behavior using another, a common exercise for understanding the relationship between stacks and queues and their underlying operations.

Given Input: Enqueue 1, 2, 3, then dequeue twice.

Expected Output:

Dequeued: 1
Dequeued: 2
💡 Hint
  • Use one stack, inStack, purely for enqueue operations by pushing new elements onto it.
  • Use a second stack, outStack, for dequeue operations.
  • When dequeuing, if outStack is empty, pop everything from inStack and push it onto outStack first, which reverses the order to FIFO.
  • Then pop from outStack to get the correct front element.
✅ Solution & Explanation

Solution:

import java.util.EmptyStackException;
import java.util.Stack;
class QueueUsingStacks {
    private Stack<Integer> inStack = new Stack<>();
    private Stack<Integer> outStack = new Stack<>();
    public void enqueue(int value) {
        inStack.push(value);
    }
    public int dequeue() {
        if (outStack.isEmpty()) {
            while (!inStack.isEmpty()) {
                outStack.push(inStack.pop());
            }
        }
        if (outStack.isEmpty()) {
            throw new EmptyStackException();
        }
        return outStack.pop();
    }
}
public class QueueUsingStacksDemo {
    public static void main(String[] args) {
        QueueUsingStacks queue = new QueueUsingStacks();
        queue.enqueue(1);
        queue.enqueue(2);
        queue.enqueue(3);
        System.out.println("Dequeued: " + queue.dequeue());
        System.out.println("Dequeued: " + queue.dequeue());
    }
}Code language: Java (java)

Explanation:

  • inStack.push(value): Adds every new element to inStack, which naturally holds elements in reverse order relative to how they were enqueued.
  • outStack.push(inStack.pop()): Transfers all elements from inStack to outStack, which reverses their order a second time and restores the original FIFO order.
  • if (outStack.isEmpty()): Only triggers the transfer when outStack has run out of elements, avoiding unnecessary work when it already has elements ready to be dequeued.

Exercise 59: Detect a Cycle in a Linked List Using Floyd's Algorithm

Problem Statement: Write a Java program that detects whether a singly linked list contains a cycle using Floyd's cycle detection algorithm, also known as the tortoise and hare technique.

Purpose: This exercise helps you practice the two-pointer technique for cycle detection, which solves the problem in constant space compared to approaches that require tracking visited nodes in a separate structure.

Given Input: A linked list 1 -> 2 -> 3 -> 4 where the last node points back to node 2, forming a cycle.

Expected Output: Cycle detected: true

💡 Hint
  • Use two pointers, slow moving one step at a time and fast moving two steps at a time.
  • If the list has a cycle, the two pointers will eventually meet at the same node.
  • If fast or fast.next reaches null, the list has no cycle.
✅ Solution & Explanation

Solution:

class Node {
    int value;
    Node next;

    Node(int value) {
        this.value = value;
    }
}

public class CycleDetection {
    public static void main(String[] args) {
        Node head = new Node(1);
        head.next = new Node(2);
        head.next.next = new Node(3);
        head.next.next.next = new Node(4);
        head.next.next.next.next = head.next;

        System.out.println("Cycle detected: " + hasCycle(head));
    }

    static boolean hasCycle(Node head) {
        Node slow = head;
        Node fast = head;

        while (fast != null && fast.next != null) {
            slow = slow.next;
            fast = fast.next.next;

            if (slow == fast) {
                return true;
            }
        }

        return false;
    }
}Code language: Java (java)

Explanation:

  • slow = slow.next: Moves the slow pointer forward by one node on every iteration.
  • fast = fast.next.next: Moves the fast pointer forward by two nodes on every iteration, so it gains on the slow pointer if a cycle exists.
  • slow == fast: Confirms a cycle exists when the two pointers eventually land on the same node, since a non-cyclic list would cause the fast pointer to reach the end first.
  • fast != null && fast.next != null: Stops the loop safely once the fast pointer runs off the end of the list, which only happens when there is no cycle.

Exercise 60: Bubble Sort with an Early-Exit Flag Optimization

Problem Statement: Write a Java program that implements bubble sort, then optimizes it with a flag that exits early once no swaps occur during a full pass, indicating the array is already sorted.

Purpose: This exercise helps you practice a simple but important optimization technique that avoids unnecessary passes over already-sorted data, improving the algorithm's best-case performance from quadratic to linear.

Given Input: numbers = {5, 1, 4, 2, 8}

Expected Output: Sorted array: [1, 2, 4, 5, 8]

💡 Hint
  • Use a nested loop structure typical of bubble sort, comparing and swapping adjacent elements.
  • Introduce a boolean flag, such as swapped, reset to false at the start of each outer loop pass.
  • Set the flag to true whenever a swap occurs during the inner loop.
  • If the flag remains false after a full pass, break out of the outer loop early since the array is already sorted.
✅ Solution & Explanation

Solution:

import java.util.Arrays;

public class OptimizedBubbleSort {
    public static void main(String[] args) {
        int[] numbers = {5, 1, 4, 2, 8};

        bubbleSort(numbers);
        System.out.println("Sorted array: " + Arrays.toString(numbers));
    }

    static void bubbleSort(int[] numbers) {
        int n = numbers.length;

        for (int i = 0; i < n - 1; i++) {
            boolean swapped = false;

            for (int j = 0; j < n - i - 1; j++) {
                if (numbers[j] > numbers[j + 1]) {
                    int temp = numbers[j];
                    numbers[j] = numbers[j + 1];
                    numbers[j + 1] = temp;
                    swapped = true;
                }
            }

            if (!swapped) {
                break;
            }
        }
    }
}Code language: Java (java)

Explanation:

  • boolean swapped = false: Resets the tracking flag at the start of every outer loop pass so it accurately reflects whether any swap happened during that specific pass.
  • swapped = true: Marks that at least one out-of-order pair was found and corrected during the current pass.
  • if (!swapped) break: Exits the sorting process early once a full pass completes without any swaps, since that means the array is already sorted and further passes are unnecessary.
  • n - i - 1: Shrinks the inner loop's range on each pass, since the largest unsorted elements are guaranteed to have bubbled into their correct position at the end of the array after each pass.

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
  • Intermediate Java Exercises
  • 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 a platform built to help developers learn by doing. Solve coding exercises, take MCQs, and run code directly in built-in online compilers.

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

MCQ Quizzes

  • Python MCQs
  • Java MCQs
  • C++ MCQs

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