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
availablefield inBookprivate and expose it only through a getter. - Add a
borrow()method inBookthat setsavailableto false only if it is currently true. - Add a
returnBook()method inBookthat setsavailableback to true. - In
Member, callbook.borrow()andbook.returnBook()instead of modifying the field directly.
✅ Solution & Explanation
Solution:
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 theBookobject 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()andabstract double perimeter()inShape. - Use
Math.PIfor 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:
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
balancefield inBankAccountso subclasses can access it directly. - Declare
withdraw(double amount)in the base class and override it in each subclass. - In
SavingsAccount, deny the withdrawal ifbalance - amountfalls below500. - In
CheckingAccount, allow the balance to go negative but not below-1000.
✅ Solution & Explanation
Solution:
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 ofwithdraw(), 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
nameandsalaryas protected fields inEmployee. - Declare
double calculateBonus()inEmployeeand override it in each subclass. - Loop through a
List[Employee]and callcalculateBonus()on each element.
✅ Solution & Explanation
Solution:
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 thoughempis declared as typeEmployee, 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
privateso no other class can instantiateLoggerdirectly. - 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:
Explanation:
private Logger(): Prevents any class outsideLoggerfrom creating new instances with thenewkeyword.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
TreeMapinstead ofHashMapif you want the grades printed in sorted order.
✅ Solution & Explanation
Solution:
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 theidfield between twoEmployeeobjects. - Override
hashCode()usingObjects.hash(id)so it stays consistent withequals(). - Add all employees to a
LinkedHashSetto remove duplicates while preserving insertion order.
✅ Solution & Explanation
Solution:
Explanation:
equals(): Defines twoEmployeeobjects as equal when theiridvalues 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()orCollections.sort().
✅ Solution & Explanation
Solution:
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:
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:
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
LinkedHashMapif you want the words printed in the order they first appear.
✅ Solution & Explanation
Solution:
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 useCollectors.toMap(...). - Use
s -> sas the key mapper andString::lengthas the value mapper. - Pass
LinkedHashMap::newas the map supplier argument to preserve insertion order.
✅ Solution & Explanation
Solution:
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 aLinkedHashMapimplementation 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 withArrays.sort(). - Compare the two sorted arrays using
Arrays.equals().
✅ Solution & Explanation
Solution:
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 usingCharacter.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
% 26to wrap around after'z'or'Z'. - To decode, shift in the opposite direction using the same logic with a negative shift.
✅ Solution & Explanation
Solution:
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:
Explanation:
expandFromCenter(text, i, i): Checks for the longest odd-length palindrome centered on a single character at indexi.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, uto count vowels. - Use
Character.isLetter()for consonants andCharacter.isDigit()for digits.
✅ Solution & Explanation
Solution:
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
StringBuilderto reverse each individual word withreverse(). - Join the reversed words back together with a single space in between.
✅ Solution & Explanation
Solution:
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
InsufficientFundsExceptionas a subclass ofExceptionwith a constructor that accepts a message. - In the withdrawal method, declare
throws InsufficientFundsExceptionin 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
mainand print the exception's message.
✅ Solution & Explanation
Solution:
Explanation:
class InsufficientFundsException extends Exception: Defines a checked exception so callers ofwithdraw()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 usinggetMessage().
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:
DataAccessExceptionandServiceException, both extendingException. - Give
ServiceExceptiona constructor that accepts both a message and aThrowable cause, passing them tosuper(message, cause). - Catch the
DataAccessExceptionand wrap it in a newServiceException, passing the caught exception as the cause. - Use
e.getCause().getMessage()to access the original exception's message.
✅ Solution & Explanation
Solution:
Explanation:
super(message, cause): Passes both the new message and the original exception to theExceptionsuperclass, linking them together.throw new ServiceException("Unable to process request", e): Wraps the low-levelDataAccessExceptioninside a higher-levelServiceExceptionwithout 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
InvalidAgeExceptionandInvalidEmailExceptionas separate subclasses ofException. - In the validation method, check the age range first and throw
InvalidAgeExceptionif 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:
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
BufferedReaderinside the parentheses of thetrystatement so it closes automatically. - Use
reader.readLine()in a loop until it returnsnull. - Catch
IOExceptionto handle cases where the file does not exist or cannot be read.
✅ Solution & Explanation
Solution:
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, returningnullwhen 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 asArrayList<T>internally to store the stack elements. push()should add to the end of the list, andpop()/peek()should operate on the last index.- Throw a
RuntimeExceptionor a custom exception whenpop()orpeek()is called on an empty stack.
✅ Solution & Explanation
Solution:
Explanation:
class Stack<T>: Declares a generic type parameterTso 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:
Explanation:
<T extends Comparable<T>>: Restricts the generic type to classes that implementComparable, guaranteeing thatcompareTo()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)andfindMax(words): Demonstrates that the same method works for both integers and strings because both types implementComparable.
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,keyof typeKandvalueof typeV. - Provide a constructor that accepts both values and simple getters for each field.
- Override
toString()to format the output asPair{key=..., value=...}.
✅ Solution & Explanation
Solution:
Explanation:
class Pair<K, V>: Declares two independent type parameters so the key and value can be of different types.getKey()andgetValue(): 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 aStringkey and anIntegervalue, 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
BufferedReaderinside try-with-resources. - Split each line using
line.split(",")to get the individual fields. - Convert the id and salary fields from
StringtointanddoubleusingInteger.parseInt()andDouble.parseDouble(). - Create a new
Employeeobject for each line and add it to the list.
✅ Solution & Explanation
Solution:
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 theEmployeeconstructor'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:
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 thatreadLine()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
synchronizedmethod 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 callnotify()to wake the other thread.
✅ Solution & Explanation
Solution:
Explanation:
synchronized void printOdd(): Ensures only one thread at a time can execute this method on the sharedNumberPrinterinstance.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()inmainto wait for both threads to finish before the program exits.
✅ Solution & Explanation
Solution:
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()andconsumer.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
ExecutorServiceusingExecutors.newFixedThreadPool(5). - Submit each task as a
Callable<Integer>usingexecutor.submit(), and store the returnedFuture<Integer>objects in a list. - Call
future.get()on eachFutureto 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:
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, unlikeRunnablewhich does not return anything.executor.submit(task): Schedules the task for execution and immediately returns aFuturerepresenting 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::newmap supplier if you want departments printed in alphabetical order.
✅ Solution & Explanation
Solution:
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 aTreeMapso 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]withmatrix[j][i]for alli < 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:
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:
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
lowandhighpointers. - If the target is found, return its index directly.
- If the loop ends without finding the target,
lowwill already point to the correct insertion index.
✅ Solution & Explanation
Solution:
Explanation:
low + (high - low) / 2: Calculates the middle index safely, avoiding potential overflow that could occur with(low + high) / 2on very large arrays.numbers[mid] < target: Narrows the search to the right half by movinglowpast the midpoint when the target is larger.return low: Once the loop ends without a match,lowhas 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 - numberand 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:
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:
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
ndisks, first moven - 1disks from source to auxiliary, then move the largest disk to the destination, then move then - 1disks from auxiliary to destination. - Each recursive call swaps the roles of source, auxiliary, and destination accordingly.
✅ Solution & Explanation
Solution:
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 topn - 1disks out of the way onto the auxiliary rod before the largest disk can move.solve(disks - 1, auxiliary, destination, source): Recursively moves the samen - 1disks 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
banda % b.
✅ Solution & Explanation
Solution:
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 thatgcd(a, b)equalsgcd(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:
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:
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 anIntegeror anotherList<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:
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:
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, hereSUMMER.
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 aswitchexpression overthis, returning the appropriate next constant for each case. - Make sure
YELLOWwraps back around toREDto complete the cycle.
✅ Solution & Explanation
Solution:
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 tonext()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
nullif it is the final state. - Add a method
canTransitionTo(OrderStatus target)that compares the target against the stored next state. - Since
DELIVEREDhas no valid next state, passnullfor it in the constructor.
✅ Solution & Explanation
Solution:
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 becausePLACEDcan only transition toSHIPPEDdirectly, 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
starttoendinclusive usingdate.plusDays(1)at each step. - Use
date.getDayOfWeek()and check it is notSATURDAYorSUNDAY. - Increment a counter each time the date passes the weekday check.
✅ Solution & Explanation
Solution:
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 aDayOfWeekenum value, which can be directly compared toSATURDAYandSUNDAY.current.plusDays(1): Advances the loop one day at a time without mutating the originalLocalDate, sinceLocalDateis 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 thejava.timepackage. - Alternatively, create a
Yearobject withYear.of(year)and callisLeap()on the instance.
✅ Solution & Explanation
Solution:
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.timeover 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(), andgetDays()on the resultingPeriodobject 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:
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()andage.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"withLocale.UKfor the UK-style output. - Use
LocalDate.parse(text, formatter)to convert a formatted string back into aLocalDate.
✅ Solution & Explanation
Solution:
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 theLocalDateobject into a human-readable string in the desired style.LocalDate.parse("25-Dec-2026", parseFormatter): Converts a formatted date string back into aLocalDateobject 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:
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 ascomororg.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
MatcherfromPattern.compile(...)and callmatcher.find()in a loop. - Use
matcher.group()to retrieve each matched substring.
✅ Solution & Explanation
Solution:
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 aMatcherthat 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:
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
StatementorPreparedStatementfor 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, andexecuteQuery()for select.
✅ Solution & Explanation
Solution:
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 aResultSetcontaining 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 thePreparedStatement. - 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:
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
LIMITparameter to the page size and theOFFSETparameter to the calculated offset.
✅ Solution & Explanation
Solution:
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 returnpageSizerows, starting after skippingoffsetrows 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
Classobject usingProduct.classorobj.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 eachFieldandMethodobject to print its name.
✅ Solution & Explanation
Solution:
Explanation:
Product.class: Obtains theClassobject representing theProducttype, which serves as the entry point for all reflection operations on that class.clazz.getDeclaredFields(): Returns an array ofFieldobjects representing every field declared in the class, regardless of its access modifier.clazz.getDeclaredMethods(): Returns an array ofMethodobjects representing every method declared directly in the class.field.getName()andmethod.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
NoSuchMethodExceptionandInvocationTargetException.
✅ Solution & Explanation
Solution:
Explanation:
clazz.getMethod("add", int.class, int.class): Looks up a public method namedaddthat accepts twointparameters, returning aMethodobject representing it.method.invoke(calculator, 5, 3): Executes the method on the givencalculatorinstance, passing5and3as arguments, just as ifcalculator.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
Nodeclass 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
nextpointer to the previous node.
✅ Solution & Explanation
Solution:
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
Nodeclass 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:
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
outStackis empty, pop everything frominStackand push it ontooutStackfirst, which reverses the order to FIFO. - Then pop from
outStackto get the correct front element.
✅ Solution & Explanation
Solution:
Explanation:
inStack.push(value): Adds every new element toinStack, which naturally holds elements in reverse order relative to how they were enqueued.outStack.push(inStack.pop()): Transfers all elements frominStacktooutStack, which reverses their order a second time and restores the original FIFO order.if (outStack.isEmpty()): Only triggers the transfer whenoutStackhas 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,
slowmoving one step at a time andfastmoving two steps at a time. - If the list has a cycle, the two pointers will eventually meet at the same node.
- If
fastorfast.nextreachesnull, the list has no cycle.
✅ Solution & Explanation
Solution:
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:
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.

Leave a Reply