This collection of Java programming interview questions and answers walks through 160+ commonly asked coding problems, from basic logic and control structures to arrays, strings, searching and sorting algorithms, and math-based problems, plus core Java OOP concepts like classes, interfaces, exception handling, generics, the Collections Framework, and streams and multithreading. Every question includes a complete, runnable Java code example, so you can practice writing the solution yourself instead of just reading about it. Use the table of contents below to jump straight to any topic.
Table of Contents
Basic Logic and Control Structures
- Write a program to check if a number is even or odd.
- Write a program to find the largest of three numbers.
- Write a program to check if a given year is a leap year.
- Write a program to calculate the factorial of a number.
- Write a program to generate the Fibonacci series up to a given number.
- Write a program to reverse a given integer number.
- Write a program to check if a number is a palindrome.
- Write a program to find the greatest common divisor (GCD) of two numbers.
- Write a program to find the least common multiple (LCM) of two numbers.
- Write a program to print the prime numbers up to a given number.
- Write a program to check if a number is prime.
- Write a program to calculate the sum of digits of a number.
- Write a program to calculate the power of a number using recursion.
- Write a program to swap two numbers without using a third variable.
- Write a program to find the sum of the first N natural numbers.
- Write a program to check if a number is an Armstrong number.
- Write a program to check if a number is a perfect number.
- Write a program to find the average of N numbers.
- Write a program to find the second largest number in an array.
- Write a program to find the sum of all prime numbers up to a given number.
Array and String Manipulation
- Write a program to reverse an array.
- Write a program to find the maximum and minimum elements in an array.
- Write a program to sort an array using bubble sort.
- Write a program to sort an array using insertion sort.
- Write a program to find the missing number in an array of integers.
- Write a program to remove duplicates from an array.
- Write a program to find the common elements between two arrays.
- Write a program to merge two sorted arrays.
- Write a program to rotate an array by K positions.
- Write a program to find the frequency of each element in an array.
- Write a program to check if a string is a palindrome.
- Write a program to count the number of vowels and consonants in a string.
- Write a program to reverse a string.
- Write a program to find the first non-repeated character in a string.
- Write a program to check if two strings are anagrams of each other.
- Write a program to find all permutations of a given string.
- Write a program to remove all white spaces from a string.
- Write a program to check if a string contains only digits.
- Write a program to find the longest substring without repeating characters.
- Write a program to count the occurrence of each character in a string.
Searching and Sorting Algorithms
- Write a program to implement binary search.
- Write a program to implement linear search.
- Write a program to sort an array using selection sort.
- Write a program to sort an array using merge sort.
- Write a program to sort an array using quick sort.
- Write a program to sort an array using heap sort.
- Write a program to find the kth smallest/largest element in an array.
- Write a program to search an element in a rotated sorted array.
- Write a program to implement the Dutch National Flag problem (sort an array of 0s, 1s, and 2s).
- Write a program to find the intersection of two sorted arrays.
Mathematical and Number-Based Problems
- Write a program to check if a number is a power of two.
- Write a program to find the square root of a number without using a built-in function.
- Write a program to find the nth Fibonacci number using dynamic programming.
- Write a program to generate all prime numbers less than N using the Sieve of Eratosthenes.
- Write a program to calculate the binomial coefficient.
- Write a program to find the sum of all digits until the sum becomes a single digit.
- Write a program to find the sum of all even numbers up to a given number.
- Write a program to print the pascal triangle.
- Write a program to find the sum of the first N Fibonacci numbers.
- Write a program to check if a number is a perfect square.
Object-Oriented Programming & Advanced Java
OOP Fundamentals
- Write a program to demonstrate defining a class and creating multiple objects in Java.
- Write a program to demonstrate a parameterized constructor in Java.
- Write a program to demonstrate the default constructor provided by Java.
- Write a program to demonstrate constructor overloading in Java.
- Write a program to demonstrate the use of the "this" keyword to resolve naming conflicts.
- Write a program to demonstrate constructor chaining using the "this()" call.
- Write a program to demonstrate calling a parent class constructor using "super".
- Write a program to demonstrate calling an overridden parent class method using "super".
- Write a program to demonstrate encapsulation using private fields and public getters/setters.
- Write a program to demonstrate method overloading in Java.
- Write a program to demonstrate method overriding in Java.
- Write a program to demonstrate a static variable shared across objects.
- Write a program to demonstrate a static method that can be called without creating an object.
- Write a program to demonstrate the difference between static and instance members.
- Write a program to demonstrate access modifiers: public, private, and protected.
- Write a program to demonstrate single inheritance in Java.
- Write a program to demonstrate multilevel inheritance in Java.
- Write a program to demonstrate an abstract class with an abstract method.
- Write a program to demonstrate the template method pattern using an abstract class.
- Write a program to demonstrate runtime polymorphism using dynamic method dispatch.
Interfaces, Polymorphism & the Object Class
- Write a program to implement a basic interface and demonstrate its method implementation.
- Write a program to demonstrate a class implementing multiple interfaces.
- Write a program to demonstrate default methods in an interface.
- Write a program to demonstrate static methods in an interface.
- Write a program to demonstrate an interface extending multiple interfaces.
- Write a program to demonstrate a functional interface using a lambda expression.
- Write a program to demonstrate runtime polymorphism using upcasting and dynamic method dispatch.
- Write a program to demonstrate polymorphism using an array of interface references.
- Write a program to override the equals() method of the Object class.
- Write a program to override the hashCode() method and verify the equals-hashCode contract using a HashSet.
- Write a program to override the toString() method of the Object class.
- Write a program to implement the Comparable interface for natural ordering.
- Write a program to implement the Comparator interface for custom ordering.
- Write a program to sort a list using multiple Comparators.
- Write a program to implement an interface using an anonymous inner class.
- Write a program to create a thread using an anonymous inner class.
- Write a program to demonstrate a local inner class.
- Write a program to demonstrate a static nested class.
- Write a program to demonstrate an enum with fields, a constructor, and methods.
- Write a program to demonstrate an enum implementing an interface with constant-specific method bodies.
Exception Handling & Generics
- Write a program to demonstrate try-catch-finally block execution in Java.
- Write a program to differentiate between checked and unchecked exceptions in Java.
- Write a program to create and use a custom checked exception in Java.
- Write a program to create and use a custom unchecked exception in Java.
- Write a program to handle multiple exception types using a multi-catch block in Java.
- Write a program to demonstrate try-with-resources using an AutoCloseable resource in Java.
- Write a program to demonstrate multiple resources and suppressed exceptions in try-with-resources.
- Write a program to demonstrate exception chaining using a cause in Java.
- Write a program to show that the finally block executes even after a return statement.
- Write a program to build a custom exception hierarchy by extending a custom exception.
- Write a program to catch, log, and rethrow an exception in Java.
- Write a program to create a generic class with a type parameter in Java.
- Write a program to create a generic method in Java.
- Write a program to use a bounded type parameter with T extends Number in Java.
- Write a program to use an upper bounded wildcard with extends in generics.
- Write a program to use a lower bounded wildcard with super in generics.
- Write a program to demonstrate varargs methods in Java.
- Write a program to create an immutable class with final fields in Java.
- Write a program to implement a generic stack using an array in Java.
- Write a program to implement a generic pair class in Java.
Java Collections Framework
- Write a program to demonstrate basic ArrayList operations.
- Write a program to demonstrate basic LinkedList operations.
- Write a program to demonstrate uniqueness of elements using HashSet.
- Write a program to store elements in sorted order using TreeSet.
- Write a program to demonstrate basic HashMap operations.
- Write a program to store keys in sorted order using TreeMap.
- Write a program to preserve insertion order using LinkedHashMap.
- Write a program to remove elements from a list safely using an Iterator.
- Write a program to traverse and modify a list in both directions using ListIterator.
- Write a program to sort a list using Collections.sort() with natural ordering.
- Write a program to sort a list of custom objects using a Comparator.
- Write a program to demonstrate a min-heap using PriorityQueue.
- Write a program to implement a stack using Deque.
- Write a program to implement a queue using Deque.
- Write a program to convert an array to a List and back to an array.
- Write a program to remove duplicates from a list using a Set.
- Write a program to merge two maps into one.
- Write a program to find the most frequent element using a HashMap.
- Write a program to create a read-only view of a list using Collections.unmodifiableList.
- Write a program to iterate a Map's entrySet.
Lambdas, Streams & Concurrency
- Write a program to implement a basic lambda expression for a functional interface.
- Write a program to define and use a custom functional interface.
- Write a program to use Function<T,R> to transform a value.
- Write a program to use Predicate<T> to test a condition.
- Write a program to use Supplier<T> to generate a value.
- Write a program to use Consumer<T> to perform an action on a value.
- Write a program to filter a list of numbers using Stream filter() and collect().
- Write a program to transform a list of strings using Stream map().
- Write a program to compute the sum of a list using Stream reduce().
- Write a program to sort a list of objects using Stream sorted() with a comparator.
- Write a program to use Optional to avoid null checks.
- Write a program to demonstrate method references using the :: operator.
- Write a program to create a thread by extending the Thread class.
- Write a program to create a thread by implementing the Runnable interface.
- Write a program to use a synchronized method to prevent a race condition.
- Write a program to use ExecutorService to run multiple tasks.
- Write a program to implement a producer-consumer scenario using wait() and notify().
- Write a program to implement a thread-safe Singleton using double-checked locking.
- Write a program to use AtomicInteger for thread-safe counting.
- Write a program to join multiple threads and wait for their completion.
Basic Logic and Control Structures
1. Write a program to check if a number is even or odd.
import java.util.Scanner;
public class EvenOddCheck {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a number: ");
int number = scanner.nextInt();
if (number % 2 == 0) {
System.out.println(number + " is even.");
} else {
System.out.println(number + " is odd.");
}
scanner.close();
}
}
2. Write a program to find the largest of three numbers.
import java.util.Scanner;
public class LargestOfThree {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
// Input three numbers
System.out.print("Enter the first number: ");
int num1 = scanner.nextInt();
System.out.print("Enter the second number: ");
int num2 = scanner.nextInt();
System.out.print("Enter the third number: ");
int num3 = scanner.nextInt();
// Determine the largest number
int largest;
if (num1 >= num2 && num1 >= num3) {
largest = num1;
} else if (num2 >= num1 && num2 >= num3) {
largest = num2;
} else {
largest = num3;
}
// Output the largest number
System.out.println("The largest number is: " + largest);
scanner.close();
}
}
3. Write a program to check if a given year is a leap year.
import java.util.Scanner;
public class LeapYearCheck {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
// Input the year
System.out.print("Enter a year: ");
int year = scanner.nextInt();
// Check if the year is a leap year
boolean isLeapYear;
if (year % 4 == 0) {
if (year % 100 == 0) {
if (year % 400 == 0) {
isLeapYear = true;
} else {
isLeapYear = false;
}
} else {
isLeapYear = true;
}
} else {
isLeapYear = false;
}
// Output the result
if (isLeapYear) {
System.out.println(year + " is a leap year.");
} else {
System.out.println(year + " is not a leap year.");
}
scanner.close();
}
}
4. Write a program to calculate the factorial of a number.
import java.util.Scanner;
public class Factorial {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
// Input the number
System.out.print("Enter a number: ");
int number = scanner.nextInt();
// Calculate factorial
long factorial = 1;
for (int i = 1; i <= number; i++) {
factorial *= i;
}
// Output the result
System.out.println("The factorial of " + number + " is: " + factorial);
scanner.close();
}
}
5. Write a program to generate the Fibonacci series up to a given number.
import java.util.Scanner;
public class FibonacciSeries {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
// Input the number up to which the Fibonacci series will be generated
System.out.print("Enter the number up to which the Fibonacci series should be generated: ");
int n = scanner.nextInt();
// Initialize the first two numbers in the Fibonacci series
int first = 0, second = 1;
System.out.print("Fibonacci Series up to " + n + ": " + first + ", " + second);
// Generate the Fibonacci series
int next;
while (true) {
next = first + second;
if (next > n) {
break;
}
System.out.print(", " + next);
first = second;
second = next;
}
scanner.close();
}
}
6. Write a program to reverse a given integer number.
import java.util.Scanner;
public class ReverseInteger {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
// Input the number
System.out.print("Enter an integer number: ");
int number = scanner.nextInt();
// Initialize the variable to store the reversed number
int reversedNumber = 0;
// Reverse the number
while (number != 0) {
int digit = number % 10; // Get the last digit
reversedNumber = reversedNumber * 10 + digit; // Add the digit to the reversed number
number = number / 10; // Remove the last digit from the original number
}
// Output the reversed number
System.out.println("Reversed Number: " + reversedNumber);
scanner.close();
}
}
7. Write a program to check if a number is a palindrome.
import java.util.Scanner;
public class PalindromeCheck {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
// Input the number
System.out.print("Enter an integer number: ");
int originalNumber = scanner.nextInt();
int reversedNumber = 0;
int temp = originalNumber;
// Reverse the number
while (temp != 0) {
int digit = temp % 10; // Get the last digit
reversedNumber = reversedNumber * 10 + digit; // Build the reversed number
temp = temp / 10; // Remove the last digit from temp
}
// Check if the original number and reversed number are the same
if (originalNumber == reversedNumber) {
System.out.println(originalNumber + " is a palindrome.");
} else {
System.out.println(originalNumber + " is not a palindrome.");
}
scanner.close();
}
}
8. Write a program to find the greatest common divisor (GCD) of two numbers.
import java.util.Scanner;
public class GCD {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
// Input two numbers
System.out.print("Enter the first number: ");
int num1 = scanner.nextInt();
System.out.print("Enter the second number: ");
int num2 = scanner.nextInt();
// Find GCD using the Euclidean algorithm
int gcd = findGCD(num1, num2);
// Output the GCD
System.out.println("The GCD of " + num1 + " and " + num2 + " is: " + gcd);
scanner.close();
}
// Method to find GCD using Euclidean algorithm
public static int findGCD(int a, int b) {
while (b != 0) {
int temp = b;
b = a % b;
a = temp;
}
return a;
}
}
9. Write a program to find the least common multiple (LCM) of two numbers.
import java.util.Scanner;
public class LCM {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
// Input two numbers
System.out.print("Enter the first number: ");
int num1 = scanner.nextInt();
System.out.print("Enter the second number: ");
int num2 = scanner.nextInt();
// Calculate LCM
int lcm = findLCM(num1, num2);
// Output the LCM
System.out.println("The LCM of " + num1 + " and " + num2 + " is: " + lcm);
scanner.close();
}
// Method to find LCM using the relationship between GCD and LCM
public static int findLCM(int a, int b) {
return (a * b) / findGCD(a, b);
}
// Method to find GCD using Euclidean algorithm
public static int findGCD(int a, int b) {
while (b != 0) {
int temp = b;
b = a % b;
a = temp;
}
return a;
}
}
10. Write a program to print the prime numbers up to a given number.
import java.util.Scanner;
public class PrimeNumbers {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
// Input the number up to which prime numbers will be printed
System.out.print("Enter a number: ");
int n = scanner.nextInt();
System.out.println("Prime numbers up to " + n + " are:");
// Print prime numbers from 2 to n
for (int i = 2; i <= n; i++) {
if (isPrime(i)) {
System.out.print(i + " ");
}
}
scanner.close();
}
// Method to check if a number is prime
public static boolean isPrime(int num) {
if (num <= 1) {
return false;
}
for (int i = 2; i <= Math.sqrt(num); i++) {
if (num % i == 0) {
return false;
}
}
return true;
}
}
11. Write a program to check if a number is prime.
import java.util.Scanner;
public class PrimeCheck {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
// Input the number to check
System.out.print("Enter an integer number: ");
int number = scanner.nextInt();
// Check if the number is prime
boolean isPrime = isPrime(number);
// Output the result
if (isPrime) {
System.out.println(number + " is a prime number.");
} else {
System.out.println(number + " is not a prime number.");
}
scanner.close();
}
// Method to check if a number is prime
public static boolean isPrime(int num) {
if (num <= 1) {
return false;
}
for (int i = 2; i <= Math.sqrt(num); i++) {
if (num % i == 0) {
return false;
}
}
return true;
}
}
12. Write a program to calculate the sum of digits of a number.
import java.util.Scanner;
public class SumOfDigits {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
// Input the number
System.out.print("Enter an integer number: ");
int number = scanner.nextInt();
// Initialize the variable to store the sum of digits
int sum = 0;
// Calculate the sum of digits
while (number != 0) {
int digit = number % 10; // Get the last digit
sum += digit; // Add the digit to the sum
number = number / 10; // Remove the last digit from the number
}
// Output the sum of digits
System.out.println("The sum of the digits is: " + sum);
scanner.close();
}
}
13. Write a program to calculate the power of a number using recursion.
import java.util.Scanner;
public class PowerCalculation {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
// Input the base and exponent
System.out.print("Enter the base number: ");
int base = scanner.nextInt();
System.out.print("Enter the exponent: ");
int exponent = scanner.nextInt();
// Calculate the power using recursion
long result = power(base, exponent);
// Output the result
System.out.println(base + " raised to the power of " + exponent + " is: " + result);
scanner.close();
}
// Recursive method to calculate power
public static long power(int base, int exponent) {
if (exponent == 0) { // Base case: any number raised to the power of 0 is 1
return 1;
} else if (exponent > 0) { // Recursive case: multiply the base with the result of power(base, exponent - 1)
return base * power(base, exponent - 1);
} else { // Handle negative exponents if needed
return 1 / power(base, -exponent); // Convert the problem to positive exponent for simplicity
}
}
}
14. Write a program to swap two numbers without using a third variable.
import java.util.Scanner;
public class SwapNumbers {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
// Input the two numbers
System.out.print("Enter the first number: ");
int num1 = scanner.nextInt();
System.out.print("Enter the second number: ");
int num2 = scanner.nextInt();
// Print the original numbers
System.out.println("Before swapping:");
System.out.println("num1 = " + num1);
System.out.println("num2 = " + num2);
// Swap the numbers without using a third variable
num1 = num1 + num2; // Step 1: Add num1 and num2, store the result in num1
num2 = num1 - num2; // Step 2: Subtract num2 from num1, store the result in num2
num1 = num1 - num2; // Step 3: Subtract the new num2 from num1, store the result in num1
// Print the swapped numbers
System.out.println("After swapping:");
System.out.println("num1 = " + num1);
System.out.println("num2 = " + num2);
scanner.close();
}
}
15. Write a program to find the sum of the first N natural numbers.
import java.util.Scanner;
public class SumOfNaturalNumbers {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
// Input the number N
System.out.print("Enter the value of N: ");
int N = scanner.nextInt();
// Calculate the sum of the first N natural numbers
int sum = calculateSum(N);
// Output the result
System.out.println("The sum of the first " + N + " natural numbers is: " + sum);
scanner.close();
}
// Method to calculate the sum of the first N natural numbers
public static int calculateSum(int N) {
// Using the formula for the sum of the first N natural numbers: sum = N * (N + 1) / 2
return N * (N + 1) / 2;
}
}
16. Write a program to check if a number is an Armstrong number.
import java.util.Scanner;
public class ArmstrongNumberCheck {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
// Input the number
System.out.print("Enter an integer number: ");
int number = scanner.nextInt();
// Check if the number is an Armstrong number
boolean isArmstrong = isArmstrongNumber(number);
// Output the result
if (isArmstrong) {
System.out.println(number + " is an Armstrong number.");
} else {
System.out.println(number + " is not an Armstrong number.");
}
scanner.close();
}
// Method to check if a number is an Armstrong number
public static boolean isArmstrongNumber(int num) {
int originalNumber = num;
int numberOfDigits = String.valueOf(num).length();
int sum = 0;
// Calculate the sum of each digit raised to the power of the number of digits
while (num != 0) {
int digit = num % 10;
sum += Math.pow(digit, numberOfDigits);
num /= 10;
}
// Check if the sum is equal to the original number
return sum == originalNumber;
}
}
17. Write a program to check if a number is a perfect number.
import java.util.Scanner;
public class PerfectNumberCheck {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
// Input the number
System.out.print("Enter an integer number: ");
int number = scanner.nextInt();
// Check if the number is a perfect number
boolean isPerfect = isPerfectNumber(number);
// Output the result
if (isPerfect) {
System.out.println(number + " is a perfect number.");
} else {
System.out.println(number + " is not a perfect number.");
}
scanner.close();
}
// Method to check if a number is a perfect number
public static boolean isPerfectNumber(int num) {
if (num <= 1) {
return false;
}
int sum = 0;
// Find the sum of the proper divisors
for (int i = 1; i <= num / 2; i++) {
if (num % i == 0) {
sum += i;
}
}
// Check if the sum of the proper divisors is equal to the original number
return sum == num;
}
}
18. Write a program to find the average of N numbers.
import java.util.Scanner;
public class AverageOfNumbers {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
// Input the number of elements
System.out.print("Enter the number of elements: ");
int N = scanner.nextInt();
// Validate input
if (N <= 0) {
System.out.println("The number of elements must be greater than zero.");
scanner.close();
return;
}
// Input the numbers and calculate the sum
double sum = 0;
for (int i = 1; i <= N; i++) {
System.out.print("Enter number " + i + ": ");
double number = scanner.nextDouble();
sum += number;
}
// Calculate the average
double average = sum / N;
// Output the result
System.out.println("The average of the " + N + " numbers is: " + average);
scanner.close();
}
}
19. Write a program to find the second largest number in an array.
import java.util.Scanner;
public class SecondLargestNumber {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
// Input the number of elements in the array
System.out.print("Enter the number of elements in the array: ");
int n = scanner.nextInt();
// Validate input
if (n < 2) {
System.out.println("Array must have at least two elements.");
scanner.close();
return;
}
// Initialize the array
int[] numbers = new int[n];
// Input the elements of the array
System.out.println("Enter the elements of the array:");
for (int i = 0; i < n; i++) {
numbers[i] = scanner.nextInt();
}
// Find the second largest number
int firstLargest = Integer.MIN_VALUE;
int secondLargest = Integer.MIN_VALUE;
for (int num: numbers) {
if (num > firstLargest) {
secondLargest = firstLargest;
firstLargest = num;
} else if (num > secondLargest && num < firstLargest) {
secondLargest = num;
}
}
// Output the result
if (secondLargest == Integer.MIN_VALUE) {
System.out.println("There is no second largest number.");
} else {
System.out.println("The second largest number is: " + secondLargest);
}
scanner.close();
}
}
20. Write a program to find the sum of all prime numbers up to a given number.
import java.util.Scanner;
public class SumOfPrimes {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
// Input the upper limit
System.out.print("Enter an upper limit: ");
int upperLimit = scanner.nextInt();
// Validate input
if (upperLimit < 2) {
System.out.println("There are no prime numbers less than 2.");
scanner.close();
return;
}
// Calculate the sum of prime numbers up to the upper limit
int sum = 0;
for (int i = 2; i <= upperLimit; i++) {
if (isPrime(i)) {
sum += i;
}
}
// Output the result
System.out.println("The sum of all prime numbers up to " + upperLimit + " is: " + sum);
scanner.close();
}
// Method to check if a number is prime
public static boolean isPrime(int num) {
if (num <= 1) {
return false;
}
if (num == 2) {
return true; // 2 is the only even prime number
}
if (num % 2 == 0) {
return false; // Exclude all other even numbers
}
for (int i = 3; i <= Math.sqrt(num); i += 2) {
if (num % i == 0) {
return false;
}
}
return true;
}
}
Array and String Manipulation
Array Problems
21. Reverse an array:
-
22. Find the maximum and minimum elements in an array:
23. Sort an array using bubble sort:
-
24. Sort an array using insertion sort:
-
25. Find the missing number in an array:
-
26. Remove duplicates from an array:
-
27. Find common elements between two arrays:
-
28. Merge two sorted arrays:
-
29. Rotate an array by K positions:
-
30. Find the frequency of each element in an array:
String Problems
-
31. Check if a string is a palindrome:
32. Count vowels and consonants in a string:
-
33. Reverse a string:
-
34. Find the first non-repeated character in a string:
-
35. Check if two strings are anagrams:
-
36. Find all permutations of a given string:
37. Remove all white spaces from a string:
-
38. Check if a string contains only digits:
-
39. Find the longest substring without repeating characters:
-
40. Count the occurrence of each character in a string:
Searching and Sorting Algorithms
41. Write a program to implement binary search.
public class BinarySearch {
public static int binarySearch(int[] arr, int target) {
int left = 0, right = arr.length - 1;
while (left <= right) {
int mid = left + (right - left) / 2;
if (arr[mid] == target) {
return mid;
} else if (arr[mid] < target) {
left = mid + 1;
} else {
right = mid - 1;
}
}
return -1; // Not found
}
public static void main(String[] args) {
int[] arr = {1, 2, 3, 4, 5};
int target = 3;
System.out.println(binarySearch(arr, target));
}
}
42. Write a program to implement linear search.
public class LinearSearch {
public static int linearSearch(int[] arr, int target) {
for (int i = 0; i < arr.length; i++) {
if (arr[i] == target) {
return i;
}
}
return -1; // Not found
}
public static void main(String[] args) {
int[] arr = {10, 20, 30, 40, 50};
int target = 30;
System.out.println(linearSearch(arr, target));
}
}
43. Write a program to sort an array using selection sort.
public class SelectionSort {
public static void selectionSort(int[] arr) {
for (int i = 0; i < arr.length - 1; i++) {
int minIndex = i;
for (int j = i + 1; j < arr.length; j++) {
if (arr[j] < arr[minIndex]) {
minIndex = j;
}
}
int temp = arr[minIndex];
arr[minIndex] = arr[i];
arr[i] = temp;
}
}
public static void main(String[] args) {
int[] arr = {64, 34, 25, 12, 22, 11, 90};
selectionSort(arr);
for (int i : arr) {
System.out.print(i + " ");
}
}
}
44. Write a program to sort an array using merge sort.
public class MergeSort {
public static void mergeSort(int[] arr) {
if (arr.length < 2) {
return;
}
int mid = arr.length / 2;
int[] left = new int[mid];
int[] right = new int[arr.length - mid];
System.arraycopy(arr, 0, left, 0, mid);
System.arraycopy(arr, mid, right, 0, arr.length - mid);
mergeSort(left);
mergeSort(right);
merge(arr, left, right);
}
private static void merge(int[] arr, int[] left, int[] right) {
int i = 0, j = 0, k = 0;
while (i < left.length && j < right.length) {
if (left[i] <= right[j]) {
arr[k++] = left[i++];
} else {
arr[k++] = right[j++];
}
}
while (i < left.length) {
arr[k++] = left[i++];
}
while (j < right.length) {
arr[k++] = right[j++];
}
}
public static void main(String[] args) {
int[] arr = {38, 27, 43, 3, 9, 82, 10};
mergeSort(arr);
for (int num : arr) {
System.out.print(num + " ");
}
}
}
45. Write a program to sort an array using quick sort.
public class QuickSort {
public static void quickSort(int[] arr, int low, int high) {
if (low < high) {
int pi = partition(arr, low, high);
quickSort(arr, low, pi - 1);
quickSort(arr, pi + 1, high);
}
}
private static int partition(int[] arr, int low, int high) {
int pivot = arr[high];
int i = low - 1;
for (int j = low; j < high; j++) {
if (arr[j] <= pivot) {
i++;
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
int temp = arr[i + 1];
arr[i + 1] = arr[high];
arr[high] = temp;
return i + 1;
}
public static void main(String[] args) {
int[] arr = {10, 80, 30, 90, 40, 50, 70};
quickSort(arr, 0, arr.length - 1);
for (int num : arr) {
System.out.print(num + " ");
}
}
}
46. Write a program to sort an array using heap sort.
public class HeapSort {
public static void heapSort(int[] arr) {
int n = arr.length;
for (int i = n / 2 - 1; i >= 0; i--) {
heapify(arr, n, i);
}
for (int i = n - 1; i >= 0; i--) {
int temp = arr[0];
arr[0] = arr[i];
arr[i] = temp;
heapify(arr, i, 0);
}
}
private static void heapify(int[] arr, int n, int i) {
int largest = i;
int left = 2 * i + 1;
int right = 2 * i + 2;
if (left < n && arr[left] > arr[largest]) {
largest = left;
}
if (right < n && arr[right] > arr[largest]) {
largest = right;
}
if (largest != i) {
int swap = arr[i];
arr[i] = arr[largest];
arr[largest] = swap;
heapify(arr, n, largest);
}
}
public static void main(String[] args) {
int[] arr = {4, 10, 3, 5, 1};
heapSort(arr);
for (int num : arr) {
System.out.print(num + " ");
}
}
}
47. Write a program to find the kth smallest/largest element in an array.
import java.util.Arrays;
public class KthSmallestLargest {
public static int findKthSmallest(int[] arr, int k) {
int[] copy = arr.clone();
Arrays.sort(copy);
return copy[k - 1];
}
public static int findKthLargest(int[] arr, int k) {
int[] copy = arr.clone();
Arrays.sort(copy);
return copy[copy.length - k];
}
public static void main(String[] args) {
int[] arr = {12, 3, 5, 7, 19};
int k = 2;
System.out.println("Kth smallest: " + findKthSmallest(arr, k));
System.out.println("Kth largest: " + findKthLargest(arr, k));
}
}
48. Write a program to search an element in a rotated sorted array.
public class RotatedBinarySearch {
public static int search(int[] arr, int target) {
int low = 0, high = arr.length - 1;
while (low <= high) {
int mid = low + (high - low) / 2;
if (arr[mid] == target) {
return mid;
}
if (arr[low] <= arr[mid]) {
if (arr[low] <= target && target < arr[mid]) {
high = mid - 1;
} else {
low = mid + 1;
}
} else {
if (arr[mid] < target && target <= arr[high]) {
low = mid + 1;
} else {
high = mid - 1;
}
}
}
return -1; // Not found
}
public static void main(String[] args) {
int[] arr = {4, 5, 6, 7, 0, 1, 2};
int target = 0;
System.out.println(search(arr, target));
}
}
49. Write a program to implement the Dutch National Flag problem (sort an array of 0s, 1s, and 2s).
public class DutchNationalFlag {
public static void sortColors(int[] arr) {
int low = 0, mid = 0, high = arr.length - 1;
while (mid <= high) {
switch (arr[mid]) {
case 0:
swap(arr, low++, mid++);
break;
case 1:
mid++;
break;
case 2:
swap(arr, mid, high--);
break;
}
}
}
private static void swap(int[] arr, int i, int j) {
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
public static void main(String[] args) {
int[] arr = {2, 0, 1, 2, 0, 1, 1};
sortColors(arr);
for (int num : arr) {
System.out.print(num + " ");
}
}
}
50. Write a program to find the intersection of two sorted arrays.
public class IntersectionSortedArrays {
public static void findIntersection(int[] arr1, int[] arr2) {
int i = 0, j = 0;
while (i < arr1.length && j < arr2.length) {
if (arr1[i] == arr2[j]) {
System.out.print(arr1[i] + " ");
i++;
j++;
} else if (arr1[i] < arr2[j]) {
i++;
} else {
j++;
}
}
}
public static void main(String[] args) {
int[] arr1 = {1, 3, 4, 5, 7};
int[] arr2 = {2, 3, 5, 6};
findIntersection(arr1, arr2);
}
}
Mathematical and Number-Based Problems
51. Write a program to check if a number is a power of two.
public class PowerOfTwo {
public static boolean isPowerOfTwo(int num) {
return num > 0 && (num & (num - 1)) == 0;
}
public static void main(String[] args) {
int num = 16;
System.out.println(isPowerOfTwo(num));
}
}
52. Write a program to find the square root of a number without using a built-in function.
public class SquareRoot {
public static int sqrt(int num) {
int left = 0, right = num;
while (left <= right) {
int mid = left + (right - left) / 2;
if (mid * mid == num) {
return mid;
} else if (mid * mid < num) {
left = mid + 1;
} else {
right = mid - 1;
}
}
return right; // Floor of the square root
}
public static void main(String[] args) {
int num = 10;
System.out.println(sqrt(num));
}
}
53. Write a program to find the nth Fibonacci number using dynamic programming.
public class Fibonacci {
public static int fibonacci(int n) {
int[] dp = new int[n + 1];
dp[0] = 0;
if (n > 0) {
dp[1] = 1;
}
for (int i = 2; i <= n; i++) {
dp[i] = dp[i - 1] + dp[i - 2];
}
return dp[n];
}
public static void main(String[] args) {
int n = 9;
System.out.println(fibonacci(n));
}
}
54. Write a program to generate all prime numbers less than N using the Sieve of Eratosthenes.
public class SieveOfEratosthenes {
public static void sieve(int n) {
boolean[] isPrime = new boolean[n + 1];
for (int i = 2; i <= n; i++) {
isPrime[i] = true;
}
for (int i = 2; i * i <= n; i++) {
if (isPrime[i]) {
for (int j = i * i; j <= n; j += i) {
isPrime[j] = false;
}
}
}
for (int i = 2; i <= n; i++) {
if (isPrime[i]) {
System.out.print(i + " ");
}
}
}
public static void main(String[] args) {
int n = 50;
sieve(n);
}
}
55. Write a program to calculate the binomial coefficient.
public class BinomialCoefficient {
public static int binomialCoefficient(int n, int k) {
int[][] dp = new int[n + 1][k + 1];
for (int i = 0; i <= n; i++) {
for (int j = 0; j <= Math.min(i, k); j++) {
if (j == 0 || j == i) {
dp[i][j] = 1;
} else {
dp[i][j] = dp[i - 1][j - 1] + dp[i - 1][j];
}
}
}
return dp[n][k];
}
public static void main(String[] args) {
int n = 5, k = 2;
System.out.println(binomialCoefficient(n, k));
}
}
56. Write a program to find the sum of all digits until the sum becomes a single digit.
public class DigitalRoot {
public static int digitalRoot(int num) {
while (num >= 10) {
int sum = 0;
while (num != 0) {
sum += num % 10;
num /= 10;
}
num = sum;
}
return num;
}
public static void main(String[] args) {
int num = 9875;
System.out.println("Digital root of " + num + " is: " + digitalRoot(num));
}
}
57. Write a program to find the sum of all even numbers up to a given number.
public class SumOfEvenNumbers {
public static int sumOfEvens(int n) {
int sum = 0;
for (int i = 2; i <= n; i += 2) {
sum += i;
}
return sum;
}
public static void main(String[] args) {
int n = 20;
System.out.println("Sum of even numbers up to " + n + " is: " + sumOfEvens(n));
}
}
58. Write a program to print the pascal triangle.
public class PascalTriangle {
public static void printPascalTriangle(int numRows) {
for (int i = 0; i < numRows; i++) {
int number = 1;
for (int j = 0; j <= i; j++) {
System.out.print(number + " ");
number = number * (i - j) / (j + 1);
}
System.out.println();
}
}
public static void main(String[] args) {
int numRows = 5;
printPascalTriangle(numRows);
}
}
59. Write a program to find the sum of the first N Fibonacci numbers.
public class SumOfFibonacci {
public static long sumOfFibonacci(int n) {
long sum = 0;
int first = 0, second = 1;
for (int i = 0; i < n; i++) {
sum += first;
int next = first + second;
first = second;
second = next;
}
return sum;
}
public static void main(String[] args) {
int n = 10;
System.out.println("Sum of the first " + n + " Fibonacci numbers is: " + sumOfFibonacci(n));
}
}
60. Write a program to check if a number is a perfect square.
public class PerfectSquareCheck {
public static boolean isPerfectSquare(int num) {
if (num < 0) {
return false;
}
int sqrt = (int) Math.sqrt(num);
return sqrt * sqrt == num;
}
public static void main(String[] args) {
int num = 49;
System.out.println(num + " is a perfect square: " + isPerfectSquare(num));
}
}
Object-Oriented Programming & Advanced Java
OOP Fundamentals
61. Write a program to demonstrate defining a class and creating multiple objects in Java.
public class ClassAndObjectDemo {
String brand;
int speed;
void display() {
System.out.println("Car: " + brand + ", Speed: " + speed + " km/h");
}
public static void main(String[] args) {
ClassAndObjectDemo car1 = new ClassAndObjectDemo();
car1.brand = "Toyota";
car1.speed = 120;
ClassAndObjectDemo car2 = new ClassAndObjectDemo();
car2.brand = "Honda";
car2.speed = 140;
car1.display();
car2.display();
}
}
62. Write a program to demonstrate a parameterized constructor in Java.
class StudentP {
String name;
int age;
StudentP(String name, int age) {
this.name = name;
this.age = age;
}
void display() {
System.out.println(name + " is " + age + " years old");
}
}
public class ParameterizedConstructorDemo {
public static void main(String[] args) {
StudentP s1 = new StudentP("Alice", 20);
StudentP s2 = new StudentP("Bob", 22);
s1.display();
s2.display();
}
}
63. Write a program to demonstrate the default constructor provided by Java.
class ItemD {
String name;
int quantity;
// No constructor defined; the compiler supplies a no-arg default constructor
}
public class DefaultConstructorDemo {
public static void main(String[] args) {
ItemD item = new ItemD();
System.out.println("Name: " + item.name);
System.out.println("Quantity: " + item.quantity);
}
}
64. Write a program to demonstrate constructor overloading in Java.
class RectangleC {
int length, width;
RectangleC() {
length = 1;
width = 1;
}
RectangleC(int side) {
length = side;
width = side;
}
RectangleC(int length, int width) {
this.length = length;
this.width = width;
}
int area() {
return length * width;
}
}
public class ConstructorOverloadingDemo {
public static void main(String[] args) {
RectangleC r1 = new RectangleC();
RectangleC r2 = new RectangleC(5);
RectangleC r3 = new RectangleC(4, 6);
System.out.println("r1 area: " + r1.area());
System.out.println("r2 area: " + r2.area());
System.out.println("r3 area: " + r3.area());
}
}
65. Write a program to demonstrate the use of the "this" keyword to resolve naming conflicts.
class PointT {
int x, y;
PointT(int x, int y) {
this.x = x;
this.y = y;
}
void show() {
System.out.println("Point(" + this.x + ", " + this.y + ")");
}
}
public class ThisKeywordDemo {
public static void main(String[] args) {
PointT p = new PointT(3, 7);
p.show();
}
}
66. Write a program to demonstrate constructor chaining using the "this()" call.
class EmployeeC {
String name;
double salary;
EmployeeC() {
this("Unknown", 0.0);
System.out.println("No-arg constructor called");
}
EmployeeC(String name) {
this(name, 30000.0);
System.out.println("One-arg constructor called");
}
EmployeeC(String name, double salary) {
this.name = name;
this.salary = salary;
System.out.println("Two-arg constructor called");
}
void display() {
System.out.println(name + " earns " + salary);
}
}
public class ConstructorChainingDemo {
public static void main(String[] args) {
EmployeeC e = new EmployeeC("Dave");
e.display();
}
}
67. Write a program to demonstrate calling a parent class constructor using "super".
class AnimalS {
String name;
AnimalS(String name) {
this.name = name;
System.out.println("Animal constructor: " + name);
}
}
class DogS extends AnimalS {
String breed;
DogS(String name, String breed) {
super(name);
this.breed = breed;
System.out.println("Dog constructor: " + breed);
}
void display() {
System.out.println(name + " is a " + breed);
}
}
public class SuperConstructorDemo {
public static void main(String[] args) {
DogS d = new DogS("Rex", "Labrador");
d.display();
}
}
68. Write a program to demonstrate calling an overridden parent class method using "super".
class ShapeM {
double area() {
return 0;
}
void info() {
System.out.println("This is a generic shape");
}
}
class CircleM extends ShapeM {
double radius;
CircleM(double radius) {
this.radius = radius;
}
@Override
double area() {
return Math.PI * radius * radius;
}
@Override
void info() {
super.info();
System.out.println("Circle area: " + area());
}
}
public class SuperMethodCallDemo {
public static void main(String[] args) {
CircleM c = new CircleM(5);
c.info();
}
}
69. Write a program to demonstrate encapsulation using private fields and public getters/setters.
class BankAccountE {
private double balance;
BankAccountE(double initial) {
balance = initial;
}
public double getBalance() {
return balance;
}
public void deposit(double amount) {
if (amount > 0) balance += amount;
}
public void withdraw(double amount) {
if (amount > 0 && amount <= balance) balance -= amount;
}
}
public class EncapsulationDemo {
public static void main(String[] args) {
BankAccountE acc = new BankAccountE(1000);
acc.deposit(500);
acc.withdraw(200);
System.out.println("Final balance: " + acc.getBalance());
}
}
70. Write a program to demonstrate method overloading in Java.
class CalculatorO {
int add(int a, int b) {
return a + b;
}
double add(double a, double b) {
return a + b;
}
int add(int a, int b, int c) {
return a + b + c;
}
}
public class MethodOverloadingDemo {
public static void main(String[] args) {
CalculatorO calc = new CalculatorO();
System.out.println("int+int: " + calc.add(2, 3));
System.out.println("double+double: " + calc.add(2.5, 3.5));
System.out.println("int+int+int: " + calc.add(1, 2, 3));
}
}
71. Write a program to demonstrate method overriding in Java.
class VehicleR {
void move() {
System.out.println("Vehicle is moving");
}
}
class BikeR extends VehicleR {
@Override
void move() {
System.out.println("Bike is riding on two wheels");
}
}
public class MethodOverridingDemo {
public static void main(String[] args) {
VehicleR v = new VehicleR();
v.move();
BikeR b = new BikeR();
b.move();
}
}
72. Write a program to demonstrate a static variable shared across objects.
class CounterS {
static int count = 0;
CounterS() {
count++;
}
}
public class StaticVariableDemo {
public static void main(String[] args) {
new CounterS();
new CounterS();
new CounterS();
System.out.println("Total objects created: " + CounterS.count);
}
}
73. Write a program to demonstrate a static method that can be called without creating an object.
class MathUtilS {
static int square(int n) {
return n * n;
}
}
public class StaticMethodDemo {
public static void main(String[] args) {
int result = MathUtilS.square(9);
System.out.println("Square of 9 is " + result);
}
}
74. Write a program to demonstrate the difference between static and instance members.
class ProductD {
static int totalProducts = 0;
int id;
String name;
ProductD(String name) {
this.name = name;
totalProducts++;
this.id = totalProducts;
}
void display() {
System.out.println("Product #" + id + ": " + name);
}
}
public class StaticVsInstanceDemo {
public static void main(String[] args) {
ProductD p1 = new ProductD("Laptop");
ProductD p2 = new ProductD("Phone");
p1.display();
p2.display();
System.out.println("Total products: " + ProductD.totalProducts);
}
}
75. Write a program to demonstrate access modifiers: public, private, and protected.
class PersonA {
private String ssn = "123-45-6789";
protected String name = "John";
public String country = "USA";
public String getSsn() {
return ssn;
}
}
class StudentA extends PersonA {
void show() {
System.out.println("Name (protected, inherited): " + name);
System.out.println("Country (public): " + country);
System.out.println("SSN (via public getter): " + getSsn());
}
}
public class AccessModifiersDemo {
public static void main(String[] args) {
StudentA s = new StudentA();
s.show();
}
}
76. Write a program to demonstrate single inheritance in Java.
class AnimalG {
void eat() {
System.out.println("Animal eats food");
}
}
class CatG extends AnimalG {
void meow() {
System.out.println("Cat says Meow");
}
}
public class SingleInheritanceDemo {
public static void main(String[] args) {
CatG cat = new CatG();
cat.eat();
cat.meow();
}
}
77. Write a program to demonstrate multilevel inheritance in Java.
class GrandparentM {
void showSurname() {
System.out.println("Surname: Sharma");
}
}
class ParentM extends GrandparentM {
void showProfession() {
System.out.println("Profession: Engineer");
}
}
class ChildM extends ParentM {
void showName() {
System.out.println("Name: Aryan");
}
}
public class MultilevelInheritanceDemo {
public static void main(String[] args) {
ChildM child = new ChildM();
child.showSurname();
child.showProfession();
child.showName();
}
}
78. Write a program to demonstrate an abstract class with an abstract method.
abstract class AbstractShapeA {
abstract double area();
void display() {
System.out.println("Area is: " + area());
}
}
class SquareA extends AbstractShapeA {
double side;
SquareA(double side) {
this.side = side;
}
double area() {
return side * side;
}
}
class TriangleA extends AbstractShapeA {
double base, height;
TriangleA(double base, double height) {
this.base = base;
this.height = height;
}
double area() {
return 0.5 * base * height;
}
}
public class AbstractClassDemo {
public static void main(String[] args) {
AbstractShapeA sq = new SquareA(4);
AbstractShapeA tr = new TriangleA(6, 3);
sq.display();
tr.display();
}
}
79. Write a program to demonstrate the template method pattern using an abstract class.
abstract class AbstractBeverageT {
final void prepareRecipe() {
boilWater();
brew();
pourInCup();
}
void boilWater() {
System.out.println("Boiling water");
}
void pourInCup() {
System.out.println("Pouring into cup");
}
abstract void brew();
}
class TeaBeverageT extends AbstractBeverageT {
void brew() {
System.out.println("Steeping the tea");
}
}
class CoffeeBeverageT extends AbstractBeverageT {
void brew() {
System.out.println("Dripping coffee through filter");
}
}
public class TemplateMethodDemo {
public static void main(String[] args) {
AbstractBeverageT tea = new TeaBeverageT();
System.out.println("Preparing tea:");
tea.prepareRecipe();
AbstractBeverageT coffee = new CoffeeBeverageT();
System.out.println("Preparing coffee:");
coffee.prepareRecipe();
}
}
80. Write a program to demonstrate runtime polymorphism using dynamic method dispatch.
class InstrumentX {
void play() {
System.out.println("Playing a generic instrument");
}
}
class GuitarX extends InstrumentX {
void play() {
System.out.println("Strumming the guitar");
}
}
class PianoX extends InstrumentX {
void play() {
System.out.println("Playing the piano keys");
}
}
public class DynamicDispatchDemo {
public static void main(String[] args) {
InstrumentX[] instruments = { new GuitarX(), new PianoX(), new InstrumentX() };
for (InstrumentX i : instruments) {
i.play();
}
}
}
Interfaces, Polymorphism & the Object Class
81. Write a program to implement a basic interface and demonstrate its method implementation.
interface Startable {
void start();
}
class Car implements Startable {
public void start() {
System.out.println("Car engine started.");
}
}
public class InterfaceBasicDemo {
public static void main(String[] args) {
Startable s = new Car();
s.start();
}
}
82. Write a program to demonstrate a class implementing multiple interfaces.
interface Swimmer {
void swim();
}
interface Flyer {
void fly();
}
class Duck implements Swimmer, Flyer {
public void swim() {
System.out.println("Duck is swimming.");
}
public void fly() {
System.out.println("Duck is flying.");
}
}
public class MultipleInterfaceDemo {
public static void main(String[] args) {
Duck duck = new Duck();
duck.swim();
duck.fly();
}
}
83. Write a program to demonstrate default methods in an interface.
interface Movable {
void move();
default void stop() {
System.out.println("Vehicle stopped.");
}
}
class Bicycle implements Movable {
public void move() {
System.out.println("Bicycle is moving.");
}
}
public class DefaultMethodDemo {
public static void main(String[] args) {
Bicycle b = new Bicycle();
b.move();
b.stop();
}
}
84. Write a program to demonstrate static methods in an interface.
interface MathOperation {
int apply(int a, int b);
static int square(int n) {
return n * n;
}
}
class Adder implements MathOperation {
public int apply(int a, int b) {
return a + b;
}
}
public class StaticMethodInterfaceDemo {
public static void main(String[] args) {
System.out.println("Square of 6: " + MathOperation.square(6));
MathOperation add = new Adder();
System.out.println("Sum: " + add.apply(3, 4));
}
}
85. Write a program to demonstrate an interface extending multiple interfaces.
interface Readable {
void read();
}
interface Writable {
void write();
}
interface ReadWrite extends Readable, Writable {
}
class Document implements ReadWrite {
public void read() {
System.out.println("Reading document.");
}
public void write() {
System.out.println("Writing document.");
}
}
public class InterfaceInheritanceDemo {
public static void main(String[] args) {
ReadWrite doc = new Document();
doc.read();
doc.write();
}
}
86. Write a program to demonstrate a functional interface using a lambda expression.
@FunctionalInterface
interface Calculator {
int calculate(int a, int b);
}
public class FunctionalInterfaceDemo {
public static void main(String[] args) {
Calculator addition = (a, b) -> a + b;
Calculator multiplication = (a, b) -> a * b;
System.out.println("Addition: " + addition.calculate(4, 5));
System.out.println("Multiplication: " + multiplication.calculate(4, 5));
}
}
87. Write a program to demonstrate runtime polymorphism using upcasting and dynamic method dispatch.
class Animal {
void sound() {
System.out.println("Animal makes a sound.");
}
}
class Dog extends Animal {
void sound() {
System.out.println("Dog barks.");
}
}
class Cat extends Animal {
void sound() {
System.out.println("Cat meows.");
}
}
public class RuntimePolymorphismDemo {
public static void main(String[] args) {
Animal a1 = new Dog();
Animal a2 = new Cat();
a1.sound();
a2.sound();
}
}
88. Write a program to demonstrate polymorphism using an array of interface references.
interface Shape {
double area();
}
class CircleShape implements Shape {
private double radius;
CircleShape(double radius) {
this.radius = radius;
}
public double area() {
return Math.PI * radius * radius;
}
}
class RectangleShape implements Shape {
private double length, width;
RectangleShape(double length, double width) {
this.length = length;
this.width = width;
}
public double area() {
return length * width;
}
}
public class PolymorphicArrayDemo {
public static void main(String[] args) {
Shape[] shapes = { new CircleShape(3), new RectangleShape(4, 5) };
for (Shape s : shapes) {
System.out.printf("Area: %.2f%n", s.area());
}
}
}
89. Write a program to override the equals() method of the Object class.
class Point {
int x, y;
Point(int x, int y) {
this.x = x;
this.y = y;
}
@Override
public boolean equals(Object obj) {
if (this == obj) return true;
if (!(obj instanceof Point)) return false;
Point p = (Point) obj;
return this.x == p.x && this.y == p.y;
}
}
public class EqualsOverrideDemo {
public static void main(String[] args) {
Point p1 = new Point(2, 3);
Point p2 = new Point(2, 3);
Point p3 = new Point(5, 6);
System.out.println("p1.equals(p2): " + p1.equals(p2));
System.out.println("p1.equals(p3): " + p1.equals(p3));
}
}
90. Write a program to override the hashCode() method and verify the equals-hashCode contract using a HashSet.
import java.util.HashSet;
class Book {
String title;
int year;
Book(String title, int year) {
this.title = title;
this.year = year;
}
@Override
public boolean equals(Object obj) {
if (!(obj instanceof Book)) return false;
Book b = (Book) obj;
return title.equals(b.title) && year == b.year;
}
@Override
public int hashCode() {
return title.hashCode() * 31 + year;
}
}
public class HashCodeOverrideDemo {
public static void main(String[] args) {
HashSet<Book> books = new HashSet<>();
books.add(new Book("Java Basics", 2020));
books.add(new Book("Java Basics", 2020));
books.add(new Book("Advanced Java", 2021));
System.out.println("Unique books count: " + books.size());
}
}
91. Write a program to override the toString() method of the Object class.
class Product {
String name;
double price;
Product(String name, double price) {
this.name = name;
this.price = price;
}
@Override
public String toString() {
return "Product[name=" + name + ", price=" + price + "]";
}
}
public class ToStringOverrideDemo {
public static void main(String[] args) {
Product p = new Product("Laptop", 55000.0);
System.out.println(p);
System.out.println("Details: " + p.toString());
}
}
92. Write a program to implement the Comparable interface for natural ordering.
import java.util.*;
class Student implements Comparable<Student> {
String name;
int marks;
Student(String name, int marks) {
this.name = name;
this.marks = marks;
}
public int compareTo(Student other) {
return this.marks - other.marks;
}
public String toString() {
return name + ":" + marks;
}
}
public class ComparableDemo {
public static void main(String[] args) {
List<Student> students = new ArrayList<>(Arrays.asList(
new Student("Amit", 78), new Student("Bina", 92), new Student("Chirag", 65)));
Collections.sort(students);
System.out.println(students);
}
}
93. Write a program to implement the Comparator interface for custom ordering.
import java.util.*;
class Employee {
String name;
int age;
Employee(String name, int age) {
this.name = name;
this.age = age;
}
public String toString() {
return name + ":" + age;
}
}
class AgeComparator implements Comparator<Employee> {
public int compare(Employee e1, Employee e2) {
return e1.age - e2.age;
}
}
public class ComparatorDemo {
public static void main(String[] args) {
List<Employee> employees = new ArrayList<>(Arrays.asList(
new Employee("Ravi", 35), new Employee("Sonia", 28), new Employee("Karan", 42)));
Collections.sort(employees, new AgeComparator());
System.out.println(employees);
}
}
94. Write a program to sort a list using multiple Comparators.
import java.util.*;
class Item {
String name;
double price;
Item(String name, double price) {
this.name = name;
this.price = price;
}
public String toString() {
return name + ":" + price;
}
}
public class MultipleComparatorDemo {
public static void main(String[] args) {
List<Item> items = new ArrayList<>(Arrays.asList(
new Item("Pen", 10.0), new Item("Book", 250.0), new Item("Eraser", 5.0)));
Comparator<Item> byName = Comparator.comparing(i -> i.name);
Comparator<Item> byPriceDesc = Comparator.comparingDouble((Item i) -> i.price).reversed();
items.sort(byName);
System.out.println("By name: " + items);
items.sort(byPriceDesc);
System.out.println("By price desc: " + items);
}
}
95. Write a program to implement an interface using an anonymous inner class.
interface ArithmeticOperation {
int perform(int a, int b);
}
public class AnonymousInnerClassDemo {
public static void main(String[] args) {
ArithmeticOperation multiply = new ArithmeticOperation() {
public int perform(int a, int b) {
return a * b;
}
};
System.out.println("Product: " + multiply.perform(6, 7));
}
}
96. Write a program to create a thread using an anonymous inner class.
public class AnonymousThreadDemo {
public static void main(String[] args) throws InterruptedException {
Thread worker = new Thread() {
public void run() {
System.out.println("Worker thread running via anonymous class.");
}
};
worker.start();
worker.join();
System.out.println("Main thread finished.");
}
}
97. Write a program to demonstrate a local inner class.
public class LocalInnerClassDemo {
static void display() {
class Message {
String text;
Message(String text) {
this.text = text;
}
void show() {
System.out.println("Local class says: " + text);
}
}
Message m = new Message("Hello from local inner class");
m.show();
}
public static void main(String[] args) {
display();
}
}
98. Write a program to demonstrate a static nested class.
public class StaticNestedClassDemo {
static class Counter {
private int count;
void increment() {
count++;
}
int getCount() {
return count;
}
}
public static void main(String[] args) {
Counter c = new Counter();
c.increment();
c.increment();
c.increment();
System.out.println("Count: " + c.getCount());
}
}
99. Write a program to demonstrate an enum with fields, a constructor, and methods.
enum Planet {
MERCURY(3.303e+23, 2.4397e6),
EARTH(5.976e+24, 6.37814e6);
private final double mass;
private final double radius;
Planet(double mass, double radius) {
this.mass = mass;
this.radius = radius;
}
double surfaceGravity() {
return 6.67300E-11 * mass / (radius * radius);
}
}
public class EnumDemo {
public static void main(String[] args) {
for (Planet p : Planet.values()) {
System.out.printf("%s gravity: %.2f%n", p, p.surfaceGravity());
}
}
}
100. Write a program to demonstrate an enum implementing an interface with constant-specific method bodies.
interface Operable {
int execute(int a, int b);
}
enum Operation implements Operable {
ADD {
public int execute(int a, int b) {
return a + b;
}
},
SUBTRACT {
public int execute(int a, int b) {
return a - b;
}
},
MULTIPLY {
public int execute(int a, int b) {
return a * b;
}
};
}
public class EnumStrategyDemo {
public static void main(String[] args) {
for (Operation op : Operation.values()) {
System.out.println(op + ": " + op.execute(10, 4));
}
}
}
Exception Handling & Generics
101. Write a program to demonstrate try-catch-finally block execution in Java.
public class TryCatchFinallyDemo {
public static void main(String[] args) {
int[] numbers = {10, 20, 0, 5};
for (int n : numbers) {
try {
int result = 100 / n;
System.out.println("100 / " + n + " = " + result);
} catch (ArithmeticException e) {
System.out.println("Error: Cannot divide by " + n + " - " + e.getMessage());
} finally {
System.out.println("Finished attempt with divisor " + n);
}
}
}
}
102. Write a program to differentiate between checked and unchecked exceptions in Java.
import java.io.IOException;
public class CheckedVsUncheckedDemo {
static void doCheckedWork() throws IOException {
throw new IOException("Checked: file not found");
}
static void doUncheckedWork() {
throw new IllegalArgumentException("Unchecked: invalid argument");
}
public static void main(String[] args) {
try {
doCheckedWork();
} catch (IOException e) {
System.out.println("Caught checked exception: " + e.getMessage());
}
try {
doUncheckedWork();
} catch (IllegalArgumentException e) {
System.out.println("Caught unchecked exception: " + e.getMessage());
}
System.out.println("Checked exceptions must be declared with 'throws' or caught at compile time.");
System.out.println("Unchecked exceptions (RuntimeException) are not checked by the compiler.");
}
}
103. Write a program to create and use a custom checked exception in Java.
class InsufficientFundsException extends Exception {
public InsufficientFundsException(String message) {
super(message);
}
}
public class CustomCheckedExceptionDemo {
static void withdraw(double balance, double amount) throws InsufficientFundsException {
if (amount > balance) {
throw new InsufficientFundsException("Cannot withdraw " + amount + ", balance is only " + balance);
}
System.out.println("Withdrew " + amount + " successfully.");
}
public static void main(String[] args) {
try {
withdraw(500.0, 700.0);
} catch (InsufficientFundsException e) {
System.out.println("Transaction failed: " + e.getMessage());
}
}
}
104. Write a program to create and use a custom unchecked exception in Java.
class InvalidAgeException extends RuntimeException {
public InvalidAgeException(String message) {
super(message);
}
}
public class CustomUncheckedExceptionDemo {
static void setAge(int age) {
if (age < 0 || age > 150) {
throw new InvalidAgeException("Age " + age + " is not valid.");
}
System.out.println("Age set to " + age);
}
public static void main(String[] args) {
setAge(30);
try {
setAge(-5);
} catch (InvalidAgeException e) {
System.out.println("Caught: " + e.getMessage());
}
}
}
105. Write a program to handle multiple exception types using a multi-catch block in Java.
public class MultiCatchDemo {
static void process(int choice) {
try {
if (choice == 1) {
int[] arr = new int[2];
arr[5] = 10;
} else if (choice == 2) {
String s = null;
s.length();
} else {
int x = Integer.parseInt("abc");
}
} catch (ArrayIndexOutOfBoundsException | NullPointerException e) {
System.out.println("Caught array/null issue: " + e.getClass().getSimpleName());
} catch (NumberFormatException e) {
System.out.println("Caught number format issue: " + e.getMessage());
}
}
public static void main(String[] args) {
process(1);
process(2);
process(3);
}
}
106. Write a program to demonstrate try-with-resources using an AutoCloseable resource in Java.
class SimpleResource implements AutoCloseable {
private String name;
public SimpleResource(String name) {
this.name = name;
System.out.println(name + " opened.");
}
public void use() {
System.out.println(name + " in use.");
}
@Override
public void close() {
System.out.println(name + " closed.");
}
}
public class TryWithResourcesDemo {
public static void main(String[] args) {
try (SimpleResource resource = new SimpleResource("FileHandle")) {
resource.use();
}
System.out.println("Resource automatically closed after try block.");
}
}
107. Write a program to demonstrate multiple resources and suppressed exceptions in try-with-resources.
class FailingResource implements AutoCloseable {
private String name;
public FailingResource(String name) {
this.name = name;
}
public void work() {
throw new RuntimeException(name + " failed during work.");
}
@Override
public void close() {
System.out.println("Closing " + name);
throw new RuntimeException(name + " failed during close.");
}
}
public class MultipleResourcesDemo {
public static void main(String[] args) {
try (FailingResource r1 = new FailingResource("Resource-A");
FailingResource r2 = new FailingResource("Resource-B")) {
r2.work();
} catch (RuntimeException e) {
System.out.println("Primary exception: " + e.getMessage());
for (Throwable suppressed : e.getSuppressed()) {
System.out.println("Suppressed: " + suppressed.getMessage());
}
}
}
}
108. Write a program to demonstrate exception chaining using a cause in Java.
class LowLevelException extends Exception {
public LowLevelException(String message) {
super(message);
}
}
class DataAccessException extends RuntimeException {
public DataAccessException(String message, Throwable cause) {
super(message, cause);
}
}
public class ExceptionChainingDemo {
static void readData() throws LowLevelException {
throw new LowLevelException("Connection timed out");
}
public static void main(String[] args) {
try {
try {
readData();
} catch (LowLevelException e) {
throw new DataAccessException("Failed to read data", e);
}
} catch (DataAccessException e) {
System.out.println("Exception: " + e.getMessage());
System.out.println("Caused by: " + e.getCause().getMessage());
}
}
}
109. Write a program to show that the finally block executes even after a return statement.
public class FinallyWithReturnDemo {
static int getValue() {
try {
System.out.println("Inside try block.");
return 10;
} finally {
System.out.println("Finally block executed even though try returned.");
}
}
public static void main(String[] args) {
int value = getValue();
System.out.println("Returned value: " + value);
}
}
110. Write a program to build a custom exception hierarchy by extending a custom exception.
class ApplicationException extends Exception {
public ApplicationException(String message) {
super(message);
}
}
class ValidationException extends ApplicationException {
public ValidationException(String message) {
super(message);
}
}
class PaymentException extends ApplicationException {
public PaymentException(String message) {
super(message);
}
}
public class ExceptionHierarchyDemo {
static void validate(int amount) throws ValidationException {
if (amount <= 0) {
throw new ValidationException("Amount must be positive.");
}
}
static void pay(int amount) throws PaymentException {
if (amount > 1000) {
throw new PaymentException("Amount exceeds payment limit.");
}
System.out.println("Paid " + amount);
}
public static void main(String[] args) {
int[] amounts = {-5, 2000, 500};
for (int amount : amounts) {
try {
validate(amount);
pay(amount);
} catch (ApplicationException e) {
System.out.println(e.getClass().getSimpleName() + ": " + e.getMessage());
}
}
}
}
111. Write a program to catch, log, and rethrow an exception in Java.
public class RethrowExceptionDemo {
static void processInput(String input) throws NumberFormatException {
try {
int value = Integer.parseInt(input);
System.out.println("Parsed value: " + value);
} catch (NumberFormatException e) {
System.out.println("Logging error before rethrow: " + e.getMessage());
throw e;
}
}
public static void main(String[] args) {
try {
processInput("42");
processInput("abc");
} catch (NumberFormatException e) {
System.out.println("Caught rethrown exception in main: " + e.getMessage());
}
}
}
112. Write a program to create a generic class with a type parameter in Java.
class Box<T> {
private T content;
public void set(T content) {
this.content = content;
}
public T get() {
return content;
}
}
public class GenericClassDemo {
public static void main(String[] args) {
Box<String> stringBox = new Box<>();
stringBox.set("Hello Generics");
System.out.println("String box contains: " + stringBox.get());
Box<Integer> intBox = new Box<>();
intBox.set(100);
System.out.println("Integer box contains: " + intBox.get());
}
}
113. Write a program to create a generic method in Java.
public class GenericMethodDemo {
static <T> void printArray(T[] array) {
for (T element : array) {
System.out.print(element + " ");
}
System.out.println();
}
static <T> T getFirst(T[] array) {
return array[0];
}
public static void main(String[] args) {
Integer[] intArray = {1, 2, 3, 4};
String[] stringArray = {"A", "B", "C"};
printArray(intArray);
printArray(stringArray);
System.out.println("First integer: " + getFirst(intArray));
System.out.println("First string: " + getFirst(stringArray));
}
}
114. Write a program to use a bounded type parameter with T extends Number in Java.
public class BoundedTypeDemo {
static <T extends Number> double sumOf(T a, T b) {
return a.doubleValue() + b.doubleValue();
}
public static void main(String[] args) {
System.out.println("Sum of ints: " + sumOf(5, 10));
System.out.println("Sum of doubles: " + sumOf(3.5, 2.5));
System.out.println("Sum mixed: " + sumOf(4, 5.5));
}
}
115. Write a program to use an upper bounded wildcard with extends in generics.
import java.util.Arrays;
import java.util.List;
public class UpperBoundedWildcardDemo {
static double sumNumbers(List<? extends Number> numbers) {
double sum = 0;
for (Number n : numbers) {
sum += n.doubleValue();
}
return sum;
}
public static void main(String[] args) {
List<Integer> integers = Arrays.asList(1, 2, 3);
List<Double> doubles = Arrays.asList(1.5, 2.5, 3.5);
System.out.println("Sum of integers: " + sumNumbers(integers));
System.out.println("Sum of doubles: " + sumNumbers(doubles));
}
}
116. Write a program to use a lower bounded wildcard with super in generics.
import java.util.ArrayList;
import java.util.List;
public class LowerBoundedWildcardDemo {
static void addIntegers(List<? super Integer> list) {
list.add(10);
list.add(20);
list.add(30);
}
public static void main(String[] args) {
List<Number> numberList = new ArrayList<>();
addIntegers(numberList);
System.out.println("Number list after adding integers: " + numberList);
List<Object> objectList = new ArrayList<>();
addIntegers(objectList);
System.out.println("Object list after adding integers: " + objectList);
}
}
117. Write a program to demonstrate varargs methods in Java.
public class VarargsDemo {
static int sum(int... numbers) {
int total = 0;
for (int n : numbers) {
total += n;
}
return total;
}
static void printAll(String prefix, Object... items) {
for (Object item : items) {
System.out.println(prefix + item);
}
}
public static void main(String[] args) {
System.out.println("Sum of 1,2,3: " + sum(1, 2, 3));
System.out.println("Sum of 5,10: " + sum(5, 10));
System.out.println("Sum of none: " + sum());
printAll("Item: ", "Pen", "Book", 42);
}
}
118. Write a program to create an immutable class with final fields in Java.
final class ImmutablePoint {
private final int x;
private final int y;
public ImmutablePoint(int x, int y) {
this.x = x;
this.y = y;
}
public int getX() {
return x;
}
public int getY() {
return y;
}
public ImmutablePoint withX(int newX) {
return new ImmutablePoint(newX, this.y);
}
@Override
public String toString() {
return "(" + x + ", " + y + ")";
}
}
public class ImmutableClassDemo {
public static void main(String[] args) {
ImmutablePoint p1 = new ImmutablePoint(3, 4);
ImmutablePoint p2 = p1.withX(10);
System.out.println("Original point: " + p1);
System.out.println("New point: " + p2);
}
}
119. Write a program to implement a generic stack using an array in Java.
import java.util.EmptyStackException;
class GenericStack<T> {
private Object[] elements = new Object[10];
private int size = 0;
public void push(T item) {
if (size == elements.length) {
elements = java.util.Arrays.copyOf(elements, size * 2);
}
elements[size++] = item;
}
@SuppressWarnings("unchecked")
public T pop() {
if (size == 0) {
throw new EmptyStackException();
}
T item = (T) elements[--size];
elements[size] = null;
return item;
}
public boolean isEmpty() {
return size == 0;
}
}
public class GenericStackDemo {
public static void main(String[] args) {
GenericStack<String> stack = new GenericStack<>();
stack.push("First");
stack.push("Second");
stack.push("Third");
while (!stack.isEmpty()) {
System.out.println("Popped: " + stack.pop());
}
}
}
120. Write a program to implement a generic pair class in Java.
class Pair<K, V> {
private final K key;
private final 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 "(" + key + ", " + value + ")";
}
}
public class GenericPairDemo {
public static void main(String[] args) {
Pair<String, Integer> nameAge = new Pair<>("Alice", 30);
Pair<Integer, Boolean> idStatus = new Pair<>(101, true);
System.out.println("Name-Age pair: " + nameAge);
System.out.println("Id-Status pair: " + idStatus);
}
}
Java Collections Framework
121. Write a program to demonstrate basic ArrayList operations.
import java.util.*;
public class ArrayListDemo {
public static void main(String[] args) {
ArrayList<String> fruits = new ArrayList<>();
fruits.add("Apple");
fruits.add("Banana");
fruits.add("Mango");
fruits.add(1, "Orange");
System.out.println("List: " + fruits);
fruits.remove("Banana");
System.out.println("After removing Banana: " + fruits);
System.out.println("Element at index 1: " + fruits.get(1));
System.out.println("Contains Mango? " + fruits.contains("Mango"));
System.out.println("Size: " + fruits.size());
}
}
122. Write a program to demonstrate basic LinkedList operations.
import java.util.*;
public class LinkedListDemo {
public static void main(String[] args) {
LinkedList<Integer> numbers = new LinkedList<>();
numbers.add(10);
numbers.add(20);
numbers.addFirst(5);
numbers.addLast(30);
System.out.println("LinkedList: " + numbers);
System.out.println("First: " + numbers.getFirst());
System.out.println("Last: " + numbers.getLast());
numbers.removeFirst();
System.out.println("After removeFirst: " + numbers);
}
}
123. Write a program to demonstrate uniqueness of elements using HashSet.
import java.util.*;
public class HashSetDemo {
public static void main(String[] args) {
HashSet<String> names = new HashSet<>();
names.add("Alice");
names.add("Bob");
names.add("Alice");
names.add("Charlie");
System.out.println("HashSet (unique elements): " + names);
System.out.println("Size: " + names.size());
System.out.println("Contains Bob? " + names.contains("Bob"));
}
}
124. Write a program to store elements in sorted order using TreeSet.
import java.util.*;
public class TreeSetDemo {
public static void main(String[] args) {
TreeSet<Integer> numbers = new TreeSet<>();
numbers.add(50);
numbers.add(10);
numbers.add(40);
numbers.add(20);
System.out.println("TreeSet (sorted order): " + numbers);
System.out.println("First: " + numbers.first());
System.out.println("Last: " + numbers.last());
}
}
125. Write a program to demonstrate basic HashMap operations.
import java.util.*;
public class HashMapDemo {
public static void main(String[] args) {
HashMap<String, Integer> ages = new HashMap<>();
ages.put("Alice", 30);
ages.put("Bob", 25);
ages.put("Charlie", 35);
System.out.println("HashMap: " + ages);
System.out.println("Bob's age: " + ages.get("Bob"));
ages.put("Bob", 26);
System.out.println("After update: " + ages);
ages.remove("Charlie");
System.out.println("After removal: " + ages);
}
}
126. Write a program to store keys in sorted order using TreeMap.
import java.util.*;
public class TreeMapDemo {
public static void main(String[] args) {
TreeMap<String, Integer> scores = new TreeMap<>();
scores.put("Charlie", 80);
scores.put("Alice", 95);
scores.put("Bob", 88);
System.out.println("TreeMap (sorted by key): " + scores);
System.out.println("First key: " + scores.firstKey());
System.out.println("Last key: " + scores.lastKey());
}
}
127. Write a program to preserve insertion order using LinkedHashMap.
import java.util.*;
public class LinkedHashMapDemo {
public static void main(String[] args) {
LinkedHashMap<String, Integer> map = new LinkedHashMap<>();
map.put("Zebra", 1);
map.put("Apple", 2);
map.put("Mango", 3);
System.out.println("LinkedHashMap (insertion order preserved):");
for (Map.Entry<String, Integer> entry : map.entrySet()) {
System.out.println(entry.getKey() + " = " + entry.getValue());
}
}
}
128. Write a program to remove elements from a list safely using an Iterator.
import java.util.*;
public class IteratorDemo {
public static void main(String[] args) {
List<Integer> numbers = new ArrayList<>(Arrays.asList(1, 2, 3, 4, 5, 6));
Iterator<Integer> it = numbers.iterator();
while (it.hasNext()) {
int n = it.next();
if (n % 2 == 0) {
it.remove();
}
}
System.out.println("After removing even numbers: " + numbers);
}
}
129. Write a program to traverse and modify a list in both directions using ListIterator.
import java.util.*;
public class ListIteratorDemo {
public static void main(String[] args) {
List<String> items = new ArrayList<>(Arrays.asList("A", "B", "C"));
ListIterator<String> lit = items.listIterator();
while (lit.hasNext()) {
String s = lit.next();
lit.set(s + s);
}
System.out.println("Forward modified: " + items);
while (lit.hasPrevious()) {
System.out.println("Backward: " + lit.previous());
}
}
}
130. Write a program to sort a list using Collections.sort() with natural ordering.
import java.util.*;
public class CollectionsSortDemo {
public static void main(String[] args) {
List<Integer> numbers = new ArrayList<>(Arrays.asList(5, 3, 8, 1, 9, 2));
System.out.println("Before sorting: " + numbers);
Collections.sort(numbers);
System.out.println("After natural order sort: " + numbers);
Collections.sort(numbers, Collections.reverseOrder());
System.out.println("After reverse order sort: " + numbers);
}
}
131. Write a program to sort a list of custom objects using a Comparator.
import java.util.*;
public class ComparatorSortDemo {
static class Employee {
String name;
int salary;
Employee(String name, int salary) {
this.name = name;
this.salary = salary;
}
public String toString() {
return name + ":" + salary;
}
}
public static void main(String[] args) {
List<Employee> employees = new ArrayList<>();
employees.add(new Employee("Alice", 50000));
employees.add(new Employee("Bob", 40000));
employees.add(new Employee("Charlie", 60000));
employees.sort(Comparator.comparingInt(e -> e.salary));
System.out.println("Sorted by salary ascending: " + employees);
employees.sort((e1, e2) -> e2.salary - e1.salary);
System.out.println("Sorted by salary descending: " + employees);
}
}
132. Write a program to demonstrate a min-heap using PriorityQueue.
import java.util.*;
public class PriorityQueueDemo {
public static void main(String[] args) {
PriorityQueue<Integer> minHeap = new PriorityQueue<>();
minHeap.add(30);
minHeap.add(10);
minHeap.add(20);
minHeap.add(5);
System.out.println("PriorityQueue (min-heap) polling order:");
while (!minHeap.isEmpty()) {
System.out.println(minHeap.poll());
}
}
}
133. Write a program to implement a stack using Deque.
import java.util.*;
public class DequeStackDemo {
public static void main(String[] args) {
Deque<Integer> stack = new ArrayDeque<>();
stack.push(1);
stack.push(2);
stack.push(3);
System.out.println("Stack after pushes: " + stack);
System.out.println("Peek: " + stack.peek());
System.out.println("Pop: " + stack.pop());
System.out.println("Stack after pop: " + stack);
}
}
134. Write a program to implement a queue using Deque.
import java.util.*;
public class DequeQueueDemo {
public static void main(String[] args) {
Deque<Integer> queue = new ArrayDeque<>();
queue.offer(1);
queue.offer(2);
queue.offer(3);
System.out.println("Queue after offers: " + queue);
System.out.println("Peek: " + queue.peek());
System.out.println("Poll: " + queue.poll());
System.out.println("Queue after poll: " + queue);
}
}
135. Write a program to convert an array to a List and back to an array.
import java.util.*;
public class ArrayToListDemo {
public static void main(String[] args) {
Integer[] array = {1, 2, 3, 4, 5};
List<Integer> list = new ArrayList<>(Arrays.asList(array));
System.out.println("Array converted to List: " + list);
list.add(6);
Integer[] backToArray = list.toArray(new Integer[0]);
System.out.println("List converted back to array: " + Arrays.toString(backToArray));
}
}
136. Write a program to remove duplicates from a list using a Set.
import java.util.*;
public class RemoveDuplicatesDemo {
public static void main(String[] args) {
List<Integer> numbers = Arrays.asList(1, 2, 2, 3, 4, 4, 5, 1);
System.out.println("Original list: " + numbers);
Set<Integer> set = new LinkedHashSet<>(numbers);
List<Integer> unique = new ArrayList<>(set);
System.out.println("List without duplicates: " + unique);
}
}
137. Write a program to merge two maps into one.
import java.util.*;
public class MergeMapsDemo {
public static void main(String[] args) {
Map<String, Integer> map1 = new HashMap<>();
map1.put("A", 1);
map1.put("B", 2);
Map<String, Integer> map2 = new HashMap<>();
map2.put("B", 20);
map2.put("C", 3);
Map<String, Integer> merged = new HashMap<>(map1);
for (Map.Entry<String, Integer> entry : map2.entrySet()) {
merged.merge(entry.getKey(), entry.getValue(), Integer::sum);
}
System.out.println("Map1: " + map1);
System.out.println("Map2: " + map2);
System.out.println("Merged map: " + merged);
}
}
138. Write a program to find the most frequent element using a HashMap.
import java.util.*;
public class MostFrequentElementDemo {
public static void main(String[] args) {
int[] numbers = {1, 3, 2, 3, 4, 3, 2, 5};
Map<Integer, Integer> frequency = new HashMap<>();
for (int n : numbers) {
frequency.put(n, frequency.getOrDefault(n, 0) + 1);
}
int mostFrequent = numbers[0];
int maxCount = 0;
for (Map.Entry<Integer, Integer> entry : frequency.entrySet()) {
if (entry.getValue() > maxCount) {
maxCount = entry.getValue();
mostFrequent = entry.getKey();
}
}
System.out.println("Frequency map: " + frequency);
System.out.println("Most frequent element: " + mostFrequent + " (count: " + maxCount + ")");
}
}
139. Write a program to create a read-only view of a list using Collections.unmodifiableList.
import java.util.*;
public class UnmodifiableListDemo {
public static void main(String[] args) {
List<String> mutable = new ArrayList<>(Arrays.asList("Red", "Green", "Blue"));
List<String> readOnly = Collections.unmodifiableList(mutable);
System.out.println("Read-only view: " + readOnly);
try {
readOnly.add("Yellow");
} catch (UnsupportedOperationException e) {
System.out.println("Cannot modify: " + e.getClass().getSimpleName());
}
mutable.add("Yellow");
System.out.println("Underlying list changed, view reflects it: " + readOnly);
}
}
140. Write a program to iterate a Map's entrySet.
import java.util.*;
public class EntrySetIterationDemo {
public static void main(String[] args) {
Map<String, Integer> inventory = new HashMap<>();
inventory.put("Pen", 100);
inventory.put("Pencil", 200);
inventory.put("Eraser", 50);
System.out.println("Iterating entrySet:");
for (Map.Entry<String, Integer> entry : inventory.entrySet()) {
System.out.println(entry.getKey() + " -> " + entry.getValue());
}
int total = 0;
for (Map.Entry<String, Integer> entry : inventory.entrySet()) {
total += entry.getValue();
}
System.out.println("Total inventory count: " + total);
}
}
Lambdas, Streams & Concurrency
141. Write a program to implement a basic lambda expression for a functional interface.
public class LambdaDemo {
interface Greeting {
void greet(String name);
}
public static void main(String[] args) {
Greeting greeting = name -> System.out.println("Hello, " + name + "!");
greeting.greet("World");
}
}
142. Write a program to define and use a custom functional interface.
interface Calculator {
int calculate(int a, int b);
}
public class CustomFunctionalInterfaceDemo {
public static void main(String[] args) {
Calculator add = (a, b) -> a + b;
Calculator multiply = (a, b) -> a * b;
System.out.println("Sum: " + add.calculate(5, 3));
System.out.println("Product: " + multiply.calculate(5, 3));
}
}
143. Write a program to use Function<T,R> to transform a value.
import java.util.function.Function;
public class FunctionDemo {
public static void main(String[] args) {
Function<Integer, Integer> square = x -> x * x;
Function<Integer, Integer> addTen = x -> x + 10;
Function<Integer, Integer> combined = square.andThen(addTen);
System.out.println("Square of 5: " + square.apply(5));
System.out.println("Square then add 10: " + combined.apply(5));
}
}
144. Write a program to use Predicate<T> to test a condition.
import java.util.function.Predicate;
public class PredicateDemo {
public static void main(String[] args) {
Predicate<Integer> isEven = n -> n % 2 == 0;
Predicate<Integer> isPositive = n -> n > 0;
System.out.println("Is 8 even? " + isEven.test(8));
System.out.println("Is -4 even and positive? " + isEven.and(isPositive).test(-4));
}
}
145. Write a program to use Supplier<T> to generate a value.
import java.util.function.Supplier;
public class SupplierDemo {
public static void main(String[] args) {
Supplier<Double> fixedValue = () -> 42.0;
Supplier<String> message = () -> "Generated on demand";
System.out.println("Value: " + fixedValue.get());
System.out.println("Message: " + message.get());
}
}
146. Write a program to use Consumer<T> to perform an action on a value.
import java.util.function.Consumer;
public class ConsumerDemo {
public static void main(String[] args) {
Consumer<String> printUpper = s -> System.out.println(s.toUpperCase());
Consumer<String> printLength = s -> System.out.println("Length: " + s.length());
Consumer<String> combined = printUpper.andThen(printLength);
combined.accept("hello");
}
}
147. Write a program to filter a list of numbers using Stream filter() and collect().
import java.util.*;
import java.util.stream.*;
public class StreamFilterCollectDemo {
public static void main(String[] args) {
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
List<Integer> evens = numbers.stream()
.filter(n -> n % 2 == 0)
.collect(Collectors.toList());
System.out.println("Even numbers: " + evens);
}
}
148. Write a program to transform a list of strings using Stream map().
import java.util.*;
import java.util.stream.*;
public class StreamMapDemo {
public static void main(String[] args) {
List<String> names = Arrays.asList("alice", "bob", "charlie");
List<Integer> lengths = names.stream()
.map(s -> s.length())
.collect(Collectors.toList());
System.out.println("Names: " + names);
System.out.println("Lengths: " + lengths);
}
}
149. Write a program to compute the sum of a list using Stream reduce().
import java.util.*;
import java.util.stream.*;
public class StreamReduceDemo {
public static void main(String[] args) {
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5);
int sum = numbers.stream().reduce(0, (a, b) -> a + b);
int product = numbers.stream().reduce(1, (a, b) -> a * b);
System.out.println("Sum: " + sum);
System.out.println("Product: " + product);
}
}
150. Write a program to sort a list of objects using Stream sorted() with a comparator.
import java.util.*;
import java.util.stream.*;
public class StreamSortedDemo {
static class Person {
String name;
int age;
Person(String name, int age) {
this.name = name;
this.age = age;
}
public String toString() {
return name + "(" + age + ")";
}
}
public static void main(String[] args) {
List<Person> people = Arrays.asList(
new Person("Bob", 30), new Person("Alice", 25), new Person("Carl", 20));
List<Person> sorted = people.stream()
.sorted(Comparator.comparingInt(p -> p.age))
.collect(Collectors.toList());
System.out.println("Sorted by age: " + sorted);
}
}
151. Write a program to use Optional to avoid null checks.
import java.util.*;
public class OptionalDemo {
static Optional<String> findUser(int id) {
if (id == 1) return Optional.of("Alice");
return Optional.empty();
}
public static void main(String[] args) {
Optional<String> user1 = findUser(1);
Optional<String> user2 = findUser(2);
System.out.println("User 1: " + user1.orElse("Not Found"));
System.out.println("User 2: " + user2.orElse("Not Found"));
user1.ifPresent(name -> System.out.println("Found: " + name));
}
}
152. Write a program to demonstrate method references using the :: operator.
import java.util.*;
import java.util.function.*;
public class MethodReferenceDemo {
public static void main(String[] args) {
List<String> names = new ArrayList<>(Arrays.asList("charlie", "alice", "bob"));
Function<String, Integer> lenFunc = String::length;
Consumer<String> printer = System.out::println;
names.sort(String::compareTo);
names.forEach(printer);
System.out.println("Length of 'alice': " + lenFunc.apply("alice"));
Supplier<ArrayList<String>> listSupplier = ArrayList::new;
List<String> newList = listSupplier.get();
newList.add("created via constructor reference");
System.out.println(newList);
}
}
153. Write a program to create a thread by extending the Thread class.
public class ThreadExtendDemo {
static class MyThread extends Thread {
public void run() {
for (int i = 1; i <= 3; i++) {
System.out.println(getName() + " - count: " + i);
}
}
}
public static void main(String[] args) throws InterruptedException {
MyThread t1 = new MyThread();
t1.setName("Thread-A");
t1.start();
t1.join();
System.out.println("Main thread finished.");
}
}
154. Write a program to create a thread by implementing the Runnable interface.
public class RunnableThreadDemo {
static class MyTask implements Runnable {
private String name;
MyTask(String name) {
this.name = name;
}
public void run() {
for (int i = 1; i <= 3; i++) {
System.out.println(name + " - count: " + i);
}
}
}
public static void main(String[] args) throws InterruptedException {
Thread t = new Thread(new MyTask("Task-1"));
t.start();
t.join();
System.out.println("Main thread finished.");
}
}
155. Write a program to use a synchronized method to prevent a race condition.
public class SynchronizedCounterDemo {
static class Counter {
private int count = 0;
synchronized void increment() {
count++;
}
int getCount() {
return count;
}
}
public static void main(String[] args) throws InterruptedException {
Counter counter = new Counter();
Runnable task = () -> {
for (int i = 0; i < 1000; i++) counter.increment();
};
Thread t1 = new Thread(task);
Thread t2 = new Thread(task);
t1.start();
t2.start();
t1.join();
t2.join();
System.out.println("Final count: " + counter.getCount());
}
}
156. Write a program to use ExecutorService to run multiple tasks.
import java.util.concurrent.*;
public class ExecutorServiceDemo {
public static void main(String[] args) throws InterruptedException {
ExecutorService executor = Executors.newFixedThreadPool(2);
for (int i = 1; i <= 4; i++) {
int taskId = i;
executor.submit(() -> System.out.println(
"Executing task " + taskId + " by " + Thread.currentThread().getName()));
}
executor.shutdown();
executor.awaitTermination(5, TimeUnit.SECONDS);
System.out.println("All tasks completed.");
}
}
157. Write a program to implement a producer-consumer scenario using wait() and notify().
import java.util.*;
public class ProducerConsumerDemo {
static class SharedQueue {
private Queue<Integer> queue = new LinkedList<>();
private int capacity = 3;
synchronized void produce(int value) throws InterruptedException {
while (queue.size() == capacity) wait();
queue.add(value);
System.out.println("Produced: " + value);
notify();
}
synchronized int consume() throws InterruptedException {
while (queue.isEmpty()) wait();
int value = queue.poll();
System.out.println("Consumed: " + value);
notify();
return value;
}
}
public static void main(String[] args) throws InterruptedException {
SharedQueue sq = new SharedQueue();
Thread producer = new Thread(() -> {
try {
for (int i = 1; i <= 5; i++) sq.produce(i);
} catch (InterruptedException e) { }
});
Thread consumer = new Thread(() -> {
try {
for (int i = 1; i <= 5; i++) sq.consume();
} catch (InterruptedException e) { }
});
producer.start();
consumer.start();
producer.join();
consumer.join();
System.out.println("Production and consumption complete.");
}
}
158. Write a program to implement a thread-safe Singleton using double-checked locking.
public class SingletonDemo {
static class Singleton {
private static volatile Singleton instance;
private Singleton() { }
static Singleton getInstance() {
if (instance == null) {
synchronized (Singleton.class) {
if (instance == null) {
instance = new Singleton();
}
}
}
return instance;
}
void showMessage() {
System.out.println("Singleton instance hash: " + this.hashCode());
}
}
public static void main(String[] args) {
Singleton s1 = Singleton.getInstance();
Singleton s2 = Singleton.getInstance();
s1.showMessage();
s2.showMessage();
System.out.println("Same instance? " + (s1 == s2));
}
}
159. Write a program to use AtomicInteger for thread-safe counting.
import java.util.concurrent.atomic.*;
public class AtomicCounterDemo {
public static void main(String[] args) throws InterruptedException {
AtomicInteger counter = new AtomicInteger(0);
Runnable task = () -> {
for (int i = 0; i < 1000; i++) counter.incrementAndGet();
};
Thread t1 = new Thread(task);
Thread t2 = new Thread(task);
t1.start();
t2.start();
t1.join();
t2.join();
System.out.println("Final counter value: " + counter.get());
}
}
160. Write a program to join multiple threads and wait for their completion.
public class JoinThreadsDemo {
public static void main(String[] args) throws InterruptedException {
Thread[] threads = new Thread[3];
for (int i = 0; i < 3; i++) {
int id = i + 1;
threads[i] = new Thread(() -> {
try {
Thread.sleep(100);
} catch (InterruptedException e) { }
System.out.println("Thread " + id + " finished execution.");
});
}
for (Thread t : threads) t.start();
for (Thread t : threads) t.join();
System.out.println("All threads have completed.");
}
}

Add your comments for more improvement!
ReplyDelete