0% found this document useful (0 votes)
23 views14 pages

Advanced Java Programming Exercises

The document contains a series of advanced Java exercises with solutions, covering topics such as reversing a LinkedList, implementing a thread-safe singleton, sorting strings by length using streams, and handling exceptions. Each exercise includes a question followed by a complete Java code solution. Additional topics include producer-consumer problems, custom annotations, and operations on collections and streams.

Uploaded by

my.misk
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
23 views14 pages

Advanced Java Programming Exercises

The document contains a series of advanced Java exercises with solutions, covering topics such as reversing a LinkedList, implementing a thread-safe singleton, sorting strings by length using streams, and handling exceptions. Each exercise includes a question followed by a complete Java code solution. Additional topics include producer-consumer problems, custom annotations, and operations on collections and streams.

Uploaded by

my.misk
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Set 1: Advanced Java Exercises

1. Question: Write a program to reverse a LinkedList without using


[Link]().​
Answer:

import [Link];

import [Link];

public class ReverseLinkedList {

public static void main(String[] args) {

LinkedList<Integer> list = new LinkedList<>();

[Link](1); [Link](2); [Link](3); [Link](4);

LinkedList<Integer> reversed = new LinkedList<>();

Iterator<Integer> iterator = [Link]();

while([Link]()) {

[Link]([Link]());

[Link](reversed);

2. Question: Implement a thread-safe singleton using double-checked


locking.​
Answer:

public class Singleton {

private static volatile Singleton instance;


private Singleton() {}

public static Singleton getInstance() {

if(instance == null) {

synchronized([Link]) {

if(instance == null) {

instance = new Singleton();

return instance;

3. Question: Write a program to sort a list of strings by length


using Java Streams.​
Answer:

import [Link].*;

import [Link].*;

public class SortByLength {

public static void main(String[] args) {

List<String> words = [Link]("Java", "Stream",


"API", "Collections");

List<String> sorted = [Link]()

.sorted([Link](String::length))
.collect([Link]());

[Link](sorted);

4. Question: Implement a custom generic class that stores two


values of any type.​
Answer:

class Pair<T, U> {

private T first;

private U second;

public Pair(T first, U second) {

[Link] = first;

[Link] = second;

public T getFirst() { return first; }

public U getSecond() { return second; }

public class Main {

public static void main(String[] args) {

Pair<String, Integer> pair = new Pair<>("Age", 25);

[Link]([Link]() + ": " +


[Link]());

}
5. Question: Write a program that reads a text file and counts the
frequency of each word.​
Answer:

import [Link].*;

import [Link].*;

public class WordFrequency {

public static void main(String[] args) throws IOException {

BufferedReader br = new BufferedReader(new


FileReader("[Link]"));

Map<String, Integer> freq = new HashMap<>();

String line;

while((line = [Link]()) != null) {

String[] words = [Link]("\\s+");

for(String word : words) {

[Link](word, [Link](word, 0) + 1);

[Link]();

[Link](freq);

6. Question: Implement a producer-consumer problem using


BlockingQueue.​
Answer:

import [Link].*;
class Producer implements Runnable {

private BlockingQueue<Integer> queue;

public Producer(BlockingQueue<Integer> q) { [Link] = q; }

public void run() {

try {

for(int i = 0; i < 10; i++) {

[Link](i);

[Link]("Produced: " + i);

} catch(InterruptedException e) { [Link](); }

class Consumer implements Runnable {

private BlockingQueue<Integer> queue;

public Consumer(BlockingQueue<Integer> q) { [Link] = q; }

public void run() {

try {

for(int i = 0; i < 10; i++) {

int val = [Link]();

[Link]("Consumed: " + val);

} catch(InterruptedException e) { [Link](); }
}

public class ProducerConsumer {

public static void main(String[] args) {

BlockingQueue<Integer> queue = new


ArrayBlockingQueue<>(5);

new Thread(new Producer(queue)).start();

new Thread(new Consumer(queue)).start();

7. Question: Implement a method to flatten a nested


List<List<Integer>> into a single List<Integer> using streams.​
Answer:

import [Link].*;

import [Link].*;

public class FlattenList {

public static void main(String[] args) {

List<List<Integer>> nested = [Link](

[Link](1,2),

[Link](3,4),

[Link](5)

);

List<Integer> flat = [Link]()

.flatMap(List::stream)

.collect([Link]());
[Link](flat);

8. Question: Write a program to detect a deadlock scenario with two


threads.​
Answer:

public class DeadlockDemo {

public static void main(String[] args) {

final Object lock1 = new Object();

final Object lock2 = new Object();

Thread t1 = new Thread(() -> {

synchronized(lock1) {

[Link]("Thread1: Holding lock1...");

try { [Link](100); } catch(Exception e) {}

synchronized(lock2) {

[Link]("Thread1: Holding lock1 &


lock2...");

});

Thread t2 = new Thread(() -> {

synchronized(lock2) {

[Link]("Thread2: Holding lock2...");

try { [Link](100); } catch(Exception e) {}

synchronized(lock1) {
[Link]("Thread2: Holding lock2 &
lock1...");

});

[Link]();

[Link]();

9. Question: Create a generic method to find the maximum element in


an array.​
Answer:

public class MaxElement {

public static <T extends Comparable<T>> T max(T[] arr) {

T max = arr[0];

for(T elem : arr) {

if([Link](max) > 0) max = elem;

return max;

public static void main(String[] args) {

Integer[] nums = {1, 5, 3, 7, 2};

[Link](max(nums));

}
10. Question: Implement a custom annotation and use reflection to
read its values at runtime.​
Answer:

import [Link].*;

import [Link].*;

@Retention([Link])

@interface Info {

String author();

String date();

@Info(author = "John", date = "2025-12-26")

class MyClass {}

public class AnnotationDemo {

public static void main(String[] args) {

Class<MyClass> obj = [Link];

if([Link]([Link])) {

Info info = [Link]([Link]);

[Link]("Author: " + [Link]());

[Link]("Date: " + [Link]());

}
11. Question: Write a Java program to remove duplicates from an
ArrayList while maintaining insertion order.​
Answer:

import [Link].*;

public class RemoveDuplicates {


public static void main(String[] args) {
List<Integer> list = [Link](1,2,3,2,4,1,5);
List<Integer> result = new ArrayList<>(new
LinkedHashSet<>(list));
[Link](result);
}
}

12. Question: Implement a thread pool with ExecutorService and


submit multiple tasks.​
Answer:

import [Link].*;

public class ThreadPoolDemo {


public static void main(String[] args) {
ExecutorService executor =
[Link](3);
for(int i = 1; i <= 5; i++) {
int task = i;
[Link](() -> [Link]("Executing
task " + task));
}
[Link]();
}
}

13. Question: Write a program to count occurrences of each


character in a string using streams.​
Answer:

import [Link].*;
import [Link].*;

public class CharFrequency {


public static void main(String[] args) {
String str = "java streams";
Map<Character, Long> freq = [Link]()
.mapToObj(c -> (char)c)

.collect([Link](c -> c, [Link]()));


[Link](freq);
}
}

14. Question: Implement a custom exception and throw it when a


negative number is passed to a method.​
Answer:

class NegativeNumberException extends Exception {


public NegativeNumberException(String message) {
super(message); }
}

public class CustomExceptionDemo {


public static void checkNumber(int num) throws
NegativeNumberException {
if(num < 0) throw new NegativeNumberException("Negative
number: " + num);
}

public static void main(String[] args) {


try { checkNumber(-5); }
catch(NegativeNumberException e) {
[Link]([Link]()); }
}
}

15. Question: Write a program to merge two sorted arrays into one
sorted array.​
Answer:

import [Link].*;

public class MergeArrays {


public static void main(String[] args) {
int[] a = {1,3,5}, b = {2,4,6};
int[] merged = new int[[Link] + [Link]];
int i=0, j=0, k=0;
while(i<[Link] && j<[Link]) merged[k++] = (a[i]<b[j])
? a[i++] : b[j++];
while(i<[Link]) merged[k++] = a[i++];
while(j<[Link]) merged[k++] = b[j++];
[Link]([Link](merged));
}
}

16. Question: Implement a class using Comparable to sort a list of


employees by salary.​
Answer:

import [Link].*;

class Employee implements Comparable<Employee> {


String name; double salary;
Employee(String n, double s) { name = n; salary = s; }
public int compareTo(Employee e) { return
[Link]([Link], [Link]); }
public String toString() { return name + ": " + salary; }
}

public class EmployeeSort {


public static void main(String[] args) {
List<Employee> list = [Link](
new Employee("Alice", 5000),
new Employee("Bob", 4000),
new Employee("Charlie", 6000)
);
[Link](list);
[Link](list);
}
}

17. Question: Write a program to implement a recursive binary


search.​
Answer:

public class RecursiveBinarySearch {


public static int binarySearch(int[] arr, int target, int
left, int right) {
if(left > right) return -1;
int mid = left + (right-left)/2;
if(arr[mid] == target) return mid;
if(arr[mid] > target) return binarySearch(arr, target,
left, mid-1);
return binarySearch(arr, target, mid+1, right);
}

public static void main(String[] args) {


int[] arr = {1,3,5,7,9};
[Link](binarySearch(arr, 5, 0, [Link]-1));
}
}

18. Question: Implement a program to read a CSV file and store each
row as an object.​
Answer:

import [Link].*;
import [Link].*;

class Person {
String name; int age;
Person(String n, int a) { name = n; age = a; }
public String toString() { return name + ", " + age; }
}

public class CSVReaderDemo {


public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new
FileReader("[Link]"));
String line;
List<Person> list = new ArrayList<>();
while((line = [Link]()) != null) {
String[] data = [Link](",");
[Link](new Person(data[0],
[Link](data[1])));
}
[Link]();
[Link](list);
}
}

19. Question: Write a program using Optional to avoid null pointer


exceptions.​
Answer:

import [Link].*;

public class OptionalDemo {


public static void main(String[] args) {
String str = null;
Optional<String> optional = [Link](str);
[Link]([Link]("Default Value"));
}
}
20. Question: Implement a program to compute the sum of squares of
all even numbers in a list using streams.​
Answer:

import [Link].*;
import [Link].*;

public class SumOfSquares {


public static void main(String[] args) {
List<Integer> numbers = [Link](1,2,3,4,5,6);
int sum = [Link]()
.filter(n -> n%2==0)
.map(n -> n*n)
.reduce(0, Integer::sum);
[Link](sum);
}
}

You might also like