Java Code Question
Java Code Question
Java interviews emphasize practical coding skills across core topics. Common areas include string and
array manipulation, object-oriented design, recursion and data structures (e.g. linked lists, stacks,
maps)【6†L222-L230】. You should be comfortable with algorithms like sorting/searching and techniques
like two-pointers or sliding windows. Expect questions on OOP principles (inheritance, interfaces,
polymorphism) and newer Java features (lambdas, streams)【6†L228-L236】. Concurrent programming is
often probed through deadlock or thread-safety scenarios【6†L232-L234】. The compiled list of 100 Java
coding problems below covers these areas, each labeled with difficulty, tags, and estimated solve time.
Concise hints and key concepts follow each problem. For deeper study, see Oracle’s Java Tutorials【26†L73-
L80】, the OpenJDK project resources, “Effective Java”【30†L61-L69】, and coding platforms like LeetCode
【32†L1-L2】 and GeeksforGeeks【34†L29-L32】.
Est.
ID Problem Statement Difficulty Tags
Time
13 Move all zeros in an array to the end. Easy Arrays, Two Pointers 5 min
1
Est.
ID Problem Statement Difficulty Tags
Time
17 Remove duplicates from a sorted array. Easy Arrays, Two Pointers 5 min
22 Search an element in a sorted rotated array. Hard Arrays, Binary Search 15 min
30 Check if all elements in a list are odd. Easy Collections, Streams 5 min
2
Est.
ID Problem Statement Difficulty Tags
Time
LinkedList, Two
37 Detect a cycle in a linked list. Hard 15 min
Pointers, HashSet
45 Next greater element for each array element. Medium Stack, Arrays 10 min
49 Check if two trees are mirrors of each other. Medium Tree 10 min
3
Est.
ID Problem Statement Difficulty Tags
Time
80 Filter and map operations on a Java Stream. Medium Java 8, Streams 10 min
4
Est.
ID Problem Statement Difficulty Tags
Time
5
• Q3. Anagram check: Hint: Sort both strings or count character frequencies (e.g. with a HashMap or
int[26]). Concept: Hashing or sorting to test character multiset equality.
• Q4. Duplicate characters: Hint: Use a HashMap or boolean array to count occurrences while
iterating. Concept: Counting frequency to find repeats.
• Q5. Remove vowels: Hint: Iterate through the string, appending only non-vowel chars. You can use
regex ( replaceAll("[aeiouAEIOU]", "") ). Concept: String traversal and regex or filtering.
• Q6. Distinct characters: Hint: Use a Set or boolean array to track seen characters, count unique
ones. Concept: Data structures (Set) for uniqueness.
• Q7. Longest common prefix: Hint: Compare characters of first string to others index by index or
sort array and compare first/last. Concept: Iterative comparison or sorting of strings.
• Q8. Replace spaces (URLify): Hint: Build a new string: replace each space with "%20". Concept: String
manipulation, careful of extra spaces or in-place (not available in Java String ).
• Q9. Only digits: Hint: Use regex like matches("\\d+") or try parsing with [Link] .
Concept: Regular expressions for pattern checking.
• Q10. Email regex: Hint: Use a pattern like ^[\\w.-]+@[\\w.-]+\\.[a-zA-Z]{2,}$ . Concept:
Regex validation.
• Q11. Reverse array: Hint: Swap elements in-place (swap arr[i] with arr[n-1-i] ). Concept:
Two-pointer technique on arrays.
• Q12. Rotate array: Hint: You can shift elements or use reverse-swap trick: reverse entire array, then
reverse subparts. Concept: Array indexing and modular arithmetic.
• Q13. Move zeros: Hint: Two-pointer (fast-slow) sweep: copy non-zeros forward, then fill rest with 0.
Concept: In-place array rearrangement.
• Q14. 2nd largest element: Hint: Track largest and second-largest in one pass. Concept: Simple linear
scan, keep two maxima.
• Q15. Stock profit (1 txn): Hint: Single pass, track min price so far and max profit. Concept: Greedy
(sliding window for max difference).
• Q16. Stock profit (mult. txns): Hint: Sum all positive differences (buy low, sell high repeatedly).
Concept: Greedy (sum of upward segments).
• Q17. Remove duplicates sorted: Hint: Two-pointer in-place: one pointer expands unique array end,
one scans. Concept: Array overwrite to remove duplicates.
• Q18. Two-sum: Hint: Use a HashMap storing needed complement -> index while scanning. Concept:
Hash table for lookup in linear time.
• Q19. Max subarray (Kadane): Hint: Track current sum; reset to 0 if negative. Concept: Dynamic
programming / greedy for subarray sum.
• Q20. Spiral matrix print: Hint: Walk boundaries (top, right, bottom, left), shrinking them each layer.
Concept: Simulation of matrix boundary traversal.
• Q21. Transpose matrix: Hint: Swap matrix[i][j] with matrix[j][i] for all i<j. Concept:
Matrix index manipulation.
• Q22. Search rotated array: Hint: Modified binary search: check which half is sorted and decide
which side target lies. Concept: Binary search in a rotated context (divide and conquer).
flowchart TB
A[Start] --> B{arr[mid] == target?}
B -- Yes --> C[Return mid index]
B -- No --> D{arr[left] <= arr[mid]?}
D -- Yes --> E{target >= arr[left] && target < arr[mid]}
D -- No --> F{target > arr[mid] && target <= arr[right]}
6
E -- Yes --> G[Search left half]
E -- No --> H[Search right half]
F -- Yes --> H
F -- No --> G
G --> I[Repeat binary search on left]
H --> J[Repeat binary search on right]
I --> C
J --> C
• Q23. Missing number: Hint: Compute expected sum 1..N and subtract actual sum, or use XOR of all.
Concept: Mathematical summation or bitwise XOR trick.
• Q24. Subarray with given sum: Hint: Two-pointer (for positives) or HashMap for prefix sums if
negatives allowed. Concept: Sliding window or prefix-sum + hash.
• Q25. Sort array: Hint: Just call [Link](arr) . Concept: Built-in sort (dual-pivot quicksort)
【6†L229-L231】.
• Q26. Merge sorted arrays: Hint: Use two indices to merge into a new array. Concept: Two-pointer
merge algorithm.
• Q27. Array intersection: Hint: Put one array into a HashSet , iterate the other to check. Concept:
Set membership testing.
• Q28. Shuffle array: Hint: Use the Fisher–Yates algorithm: swap each element with a random later
one. Concept: Randomization of arrays.
• Q29. Sum all elements: Hint: Loop and accumulate total. Concept: Simple reduction (can use streams
[Link](arr).sum() ).
• Q30. All odd check: Hint: Iterate or use stream().allMatch(x -> x%2!=0) . Concept: Stream
filters or predicate testing on collections.
• Q31. Concatenate lists: Hint: Add all elements of list B to list A (or vice versa). Concept: Collections
merging (e.g. addAll ).
• Q32. Duplicate in N+1: Hint: Use a HashSet or Floyd’s cycle detection on “value as next index”.
Concept: Pigeonhole principle, cycle detection.
• Q33. Alternate pos/neg: Hint: Partition positives/negatives then interleave; or use two pointers
swapping. Concept: Array reordering by sign.
• Q35. Leap year check: Hint: Year is leap if divisible by 4, but not by 100 unless also by 400. Concept:
Control flow and modulus.
• Q36. Reverse linked list: Hint: Iteratively update next pointers: keep track of previous node.
Concept: Pointer manipulation in linked lists.
• Q37. Detect cycle (Floyd): Hint: Use slow and fast pointers; if they meet, a cycle exists. Concept: Two-
pointer cycle detection.
• Q38. Merge sorted lists: Hint: Iterate both lists, appending the smaller current node to result.
Concept: Linked list merge like merge-sort.
• Q39. Remove nth from end: Hint: Use two-pointer: advance first by n, then move both until first hits
end. Concept: Gap technique on lists.
• Q40. Palindrome list: Hint: Reverse second half and compare to first half. Concept: Linked list
manipulation + palindrome check.
• Q41. Stack via queues: Hint: On push, enqueue to empty queue then pour old queue into it. Pop =
dequeue. Concept: Data structure emulation using queues.
• Q42. Queue via stacks: Hint: Use two stacks: push to stack1 ; on dequeue, if stack2 empty,
transfer all from stack1 then pop. Concept: Data structure emulation using stacks.
7
• Q43. Postfix evaluation: Hint: Use a stack: on operand push, on operator pop two and apply.
Concept: Stack-based expression evaluation.
• Q44. Balanced parentheses: Hint: Push opening brackets, pop on matching closing; ensure stack
empty at end. Concept: Stack for matching delimiters.
• Q45. Next greater element: Hint: Use a stack to maintain candidates: iterate array, pop from stack
when current is greater. Concept: Monotonic stack technique.
• Q46. Inorder tree traversal: Hint: Recursion on left, node, then right. Concept: DFS traversal
(inorder).
• Q47. Check BST: Hint: Recursively ensure each node’s value lies in valid min/max bounds. Concept:
Recursive tree validation.
• Q48. LCA in BST: Hint: Walk down from root: if both nodes < root go left, if both > root go right, else
root is LCA. Concept: Use BST ordering.
• Q49. Mirror trees: Hint: Recursively check left1 vs right2 and vice versa. Concept: Tree
symmetry check.
• Q50. Level-order traversal: Hint: Use a queue: enqueue root, then loop: dequeue node, enqueue its
children. Concept: BFS on trees.
• Q51. BFS graph: Hint: Use a queue; mark visited to avoid repeats. Concept: Graph breadth-first
search.
• Q52. Cycle in directed graph: Hint: Use DFS with coloring (recursion stack) or Kahn’s algorithm for
cycle. Concept: Graph cycle detection via DFS.
• Q53. Topological sort: Hint: Use DFS post-order or Kahn’s algorithm with in-degrees. Concept:
Ordering in DAGs using DFS or BFS.
• Q54. DFS graph: Hint: Recursion or explicit stack from a start node, mark visited. Concept: Graph
depth-first search.
• Q55. Binary search: Hint: Repeatedly compare target to mid of current range, halve range. Concept:
Divide-and-conquer search; see flowchart above.
• Q56. Merge sort: Hint: Recursively split array, sort halves, then merge. Concept: Divide-and-conquer
sort.
• Q57. Quick sort: Hint: Choose a pivot, partition array into < and > pivot, recurse on partitions.
Concept: Divide-and-conquer sort.
• Q58. k-th smallest (heap): Hint: Use a min-heap (or max-heap of size k). Concept: Priority queue
selection.
• Q59. Count inversions: Hint: Modify merge sort to count cross-inversions. Concept: Divide-and-
conquer counting.
• Q60. Prime check: Hint: Test divisibility up to √n. Concept: Loop / optimized trial division.
• Q61. Fibonacci (recursive): Hint: return fib(n-1)+fib(n-2) with base cases. Concept: Simple
recursion (inefficient).
• Q62. Factorial: Hint: Loop multiplication or recursive. Concept: Recursion/iteration of mathematical
formula.
• Q63. Fibonacci (DP): Hint: Use an array or variables to iteratively compute up to n. Concept: Dynamic
programming / iterative optimization.
• Q64. GCD (Euclid): Hint: Use recursive gcd(a,b) = gcd(b, a%b) . Concept: Euclidean algorithm.
• Q65. LCM: Hint: lcm(a,b) = |a*b| / gcd(a,b) . Concept: Math formula using GCD.
• Q66. Power of two: Hint: Check n > 0 && (n & (n-1)) == 0 . Concept: Bit manipulation trick.
• Q67. LIS: Hint: DP O(n^2) or patience sorting O(n log n). Concept: Longest increasing subsequence
problem.
• Q68. 0/1 Knapsack: Hint: DP table dp[i][w] for choices. Concept: Classic DP optimization.
8
• Q69. Coin Change: Hint: DP using min-coin table or greedy if coins fit. Concept: Unbounded knapsack
variant.
• Q70. LCS: Hint: DP table comparing prefixes of two strings. Concept: String DP.
• Q71. Word Break: Hint: DP or BFS on positions with a dictionary check. Concept: DP or backtracking
with memo.
• Q72. Inheritance example: Hint: Write a subclass extending a superclass and override a method.
Concept: Polymorphism (method overriding) in Java.
• Q73. Interface default methods: Hint: Define an interface with a default method; implement it in a
class. Concept: Java 8 interface enhancements.
• Q74. Diamond problem with interfaces: Hint: Show two interfaces with same default method and a
class implements both (resolving conflict). Concept: Multiple inheritance via interfaces.
classDiagram
interface InterfaceA {
+defaultMethod()
}
interface InterfaceB {
+defaultMethod()
}
class Implementer implements InterfaceA, InterfaceB {
+defaultMethod()
}
• Q75. Overloading vs Overriding: Hint: Give examples: same name diff params (overload) vs same
signature in subclass (override). Concept: Compile-time vs runtime polymorphism.
• Q76. Singleton pattern: Hint: Use a private constructor and a public static instance method (with or
without synchronization). Concept: Design pattern ensuring one instance.
• Q77. Factory pattern: Hint: Define a Factory class that creates objects based on input. Concept:
Encapsulating object creation.
• Q78. Observer pattern: Hint: Show Subject and Observer interfaces with add/remove/notify
methods. Concept: Publish-subscribe pattern.
• Q79. Lambda sort: Hint: E.g. [Link]((a,b) -> [Link]() - [Link]()); . Concept:
Java 8 lambdas for Comparator .
• Q80. Stream filter/map: Hint: E.g. [Link]().filter(x->x>0).map(x-
>x*x).collect(...) . Concept: Functional operations on streams.
• Q81. Sort HashMap by values: Hint: Stream the entry set, sort by value, then collect. Concept: Using
Java Streams to sort entries.
• Q82. Generics example: Hint: Define class Box<T>{T value;} , and a generic method <T> T
first(T[] arr) . Concept: Compile-time type safety with generics.
• Q83. Optional usage: Hint: Use [Link](x).orElse(defaultVal) . Concept:
Avoiding null checks with Optional .
• Q84. Date formatting: Hint:
[Link]().format([Link]("yyyy-MM-dd")) . Concept: Java
8+ Date-Time API.
• Q85. Deadlock creation: Hint: Two threads each lock lockA then lockB (and vice versa). Concept:
Thread synchronization and deadlock conditions.
9
• Q86. Producer-Consumer: Hint: Use a blocking queue or wait/notify in shared buffer. Concept: Inter-
thread communication (e.g. BlockingQueue ).
• Q87. Synchronized example: Hint: Wrap shared resource access in synchronized(lock)
{ ... } . Concept: Mutual exclusion for thread safety.
• Q88. join() vs sleep(): Hint: join() waits for a thread to finish; sleep() pauses current thread.
Concept: Thread coordination vs delay.
• Q89. ConcurrentHashMap: Hint: Show updating map from multiple threads without explicit locks.
Concept: Thread-safe collections.
• Q90. Read file line by line: Hint: Use BufferedReader or [Link](Path) in try-with-
resources. Concept: I/O streams and resource management.
• Q91. Write file: Hint: Use BufferedWriter , PrintWriter , or [Link] . Concept: File I/O.
• Q92. Serialization: Hint: ObjectOutputStream to write, ObjectInputStream to read an object.
Concept: Java object serialization/deserialization.
• Q93. Try-with-resources: Hint: try (Resource res = ...) { ... } auto-closes. Concept:
Resource management and exception safety (Java 7+).
• Q94. Email regex: Hint: Pattern like ^[\\w.-]+@[\\w.-]+\\.[a-zA-Z]{2,}$ . Concept: Regular
expression for emails.
• Q95. Letters-only regex: Hint: Use matches("[a-zA-Z]+") . Concept: Regex character classes.
• Q96. Implement Stack: Hint: Use an array or ArrayList internally with push/pop. Concept: Classic
stack data structure (LIFO).
• Q97. Implement Queue: Hint: Use a linked list or circular array for FIFO. Concept: Classic queue data
structure (FIFO).
• Q98. Command-line args: Hint: Access String[] args in main and print. Concept: Java program
arguments.
• Q99. Palindrome integer: Hint: Reverse digits (without extra storage) or compare string. Concept:
Numeric palindrome check.
• Q100. Integer to binary: Hint: Repeatedly divide by 2 and collect remainders (or use
[Link] ). Concept: Manual base conversion.
Representative Solutions
Below are 20 full solutions (spread of topics/difficulty). Each includes runnable Java code and a brief
explanation. (All code targets Java 8+ compatibility.)
10
}
}
Explanation: We use [Link]() for brevity. This runs in Java 8+. The key concept is that
StringBuilder can efficiently build a reversed string【27†L1-L3】 (since String itself is immutable).
import [Link];
public class AnagramCheck {
public static boolean areAnagrams(String s1, String s2) {
if ([Link]() != [Link]()) return false;
char[] a = [Link]().toCharArray();
char[] b = [Link]().toCharArray();
[Link](a);
[Link](b);
return [Link](a, b);
}
public static void main(String[] args) {
[Link](areAnagrams("Listen", "Silent")); // true
[Link](areAnagrams("Hello", "World")); // false
}
}
Explanation: Sort both strings’ character arrays and compare. Sorting is O(n log n) . This tests string
manipulation and sorting. (Java version: any Java 8+.)
import [Link];
public class RotateArray {
public static int[] rotate(int[] arr, int k) {
int n = [Link];
k %= n;
int[] result = new int[n];
for (int i = 0; i < n; i++) {
result[(i + k) % n] = arr[i];
}
return result;
}
public static void main(String[] args) {
int[] arr = {1,2,3,4,5};
[Link]([Link](rotate(arr, 2))); // [4,5,1,2,3]
11
}
}
Explanation: We compute the new index (i+k)%n for each element. This uses an extra array but is
straightforward. Concept: array index math.
Explanation: We keep a running current sum and reset if it becomes negative. maxSoFar tracks the
best sum. Concept: Kadane’s algorithm (linear-time).
import [Link].*;
public class SpiralPrint {
public static List<Integer> spiral(int[][] mat) {
List<Integer> result = new ArrayList<>();
int top=0, bottom=[Link]-1, left=0, right=mat[0].length-1;
while (top <= bottom && left <= right) {
for (int j = left; j <= right; j++) [Link](mat[top][j]);
top++;
for (int i = top; i <= bottom; i++) [Link](mat[i][right]);
right--;
if (top <= bottom) {
for (int j = right; j >= left; j--) [Link](mat[bottom][j]);
bottom--;
}
if (left <= right) {
for (int i = bottom; i >= top; i--) [Link](mat[i][left]);
left++;
12
}
}
return result;
}
public static void main(String[] args) {
int[][] mat = {{1,2,3},{4,5,6},{7,8,9}};
[Link](spiral(mat)); // [1,2,3,6,9,8,7,4,5]
}
}
Explanation: We walk the matrix boundaries in layers: top row L→R, right col T→B, bottom row R→L, left col
B→T. Concept: iterative simulation of spiral order.
Explanation: Classic modified binary search: at each step determine which half is sorted and decide where
target lies. Concept: binary search in a rotated array.
13
public class ListNode {
int val;
ListNode next;
ListNode(int x) { val = x; }
}
public class ReverseLinkedList {
public static ListNode reverse(ListNode head) {
ListNode prev = null, curr = head;
while (curr != null) {
ListNode nextNode = [Link];
[Link] = prev;
prev = curr;
curr = nextNode;
}
return prev;
}
// Utility to build list and print it
public static void main(String[] args) {
ListNode head = new ListNode(1);
[Link] = new ListNode(2); [Link] = new ListNode(3);
ListNode rev = reverse(head);
while (rev != null) { [Link]([Link] + " "); rev = [Link]; }
// Output: 3 2 1
}
}
Explanation: We iterate through the list, reversing the next pointers one by one. Concept: in-place linked-
list pointer manipulation.
14
[Link] = new ListNode(-4);
[Link] = [Link]; // create cycle to node 2
[Link](hasCycle(head)); // true
}
}
Explanation: Floyd’s tortoise-and-hare algorithm: a slow pointer moves one step, fast moves two. If cycle
exists, they meet. Concept: two-pointer technique for cycle detection.
import [Link];
public class PalindromeLinkedList {
public static boolean isPalindrome(ListNode head) {
if (head == null) return true;
Stack<Integer> stack = new Stack<>();
ListNode curr = head;
while (curr != null) { [Link]([Link]); curr = [Link]; }
curr = head;
while (curr != null) {
if ([Link] != [Link]()) return false;
curr = [Link];
}
return true;
}
public static void main(String[] args) {
ListNode head = new ListNode(1);
[Link] = new ListNode(2);
[Link] = new ListNode(1);
[Link](isPalindrome(head)); // true
}
}
Explanation: Push values onto a stack, then compare while popping. If all match, it’s a palindrome. Concept:
Using stack to compare forward/backwards.
import [Link];
import [Link];
public class StackWithQueues {
private Queue<Integer> q1 = new LinkedList<>();
private Queue<Integer> q2 = new LinkedList<>();
15
[Link](x);
while (![Link]()) [Link]([Link]());
// swap names
Queue<Integer> temp = q1;
q1 = q2;
q2 = temp;
}
public int pop() {
return [Link]();
}
public static void main(String[] args) {
StackWithQueues stack = new StackWithQueues();
[Link](1); [Link](2); [Link](3);
[Link]([Link]()); // 3
[Link]([Link]()); // 2
}
}
Explanation: On push, enqueue new element into empty q2, pour all elements from q1 into q2, then swap
queues. Pop just dequeues. Concept: Emulate a LIFO stack using FIFO queues.
import [Link];
public class QueueWithStacks {
private Stack<Integer> stackIn = new Stack<>();
private Stack<Integer> stackOut = new Stack<>();
16
Explanation: enqueue pushes to stackIn . On dequeue , if stackOut is empty, transfer all from
stackIn to stackOut (reversing order), then pop. Concept: Use two stacks to model FIFO.
Explanation: Standard binary search on sorted array. Uses bitwise unsigned shift >>> to avoid overflow
(Java 8+). Concept: divide-and-conquer search.
import [Link];
public class MergeSortExample {
public static void mergeSort(int[] arr) {
if ([Link] <= 1) return;
int mid = [Link] / 2;
int[] left = [Link](arr, 0, mid);
int[] right = [Link](arr, mid, [Link]);
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 < [Link] && j < [Link]) {
arr[k++] = (left[i] <= right[j]) ? left[i++] : right[j++];
}
while (i < [Link]) arr[k++] = left[i++];
17
while (j < [Link]) arr[k++] = right[j++];
}
public static void main(String[] args) {
int[] arr = {5,2,4,6,1,3};
mergeSort(arr);
[Link]([Link](arr)); // [1,2,3,4,5,6]
}
}
Explanation: Recursively split the array and merge sorted halves. Concept: classic divide-and-conquer (n log
n) sorting.
import [Link];
public class QuickSortExample {
public static void quickSort(int[] arr, int low, int high) {
if (low < high) {
int p = partition(arr, low, high);
quickSort(arr, low, p - 1);
quickSort(arr, p + 1, high);
}
}
private static int partition(int[] arr, int low, int high) {
int pivot = arr[high];
int i = low;
for (int j = low; j < high; j++) {
if (arr[j] <= pivot) {
int temp = arr[i]; arr[i] = arr[j]; arr[j] = temp;
i++;
}
}
// swap pivot to correct place
int temp = arr[i]; arr[i] = arr[high]; arr[high] = temp;
return i;
}
public static void main(String[] args) {
int[] arr = {4,2,7,1,3};
quickSort(arr, 0, [Link]-1);
[Link]([Link](arr)); // [1,2,3,4,7]
}
}
Explanation: Pick the last element as pivot, partition the array around it, then sort subarrays. Concept: in-
place recursive quicksort.
18
Q79. Lambda sort (Easy):
import [Link].*;
public class LambdaSort {
public static void main(String[] args) {
List<String> names = [Link]("Alice", "Bob", "Charly");
// sort by string length using lambda
[Link]((a, b) -> [Link]([Link](), [Link]()));
[Link](names); // [Bob, Alice, Charly]
}
}
Explanation: We use [Link] with a lambda comparator. Concept: Java 8 lambdas simplify sorting logic.
import [Link].*;
import [Link].*;
public class StreamExample {
public static void main(String[] args) {
List<Integer> nums = [Link](-2, 3, -1, 4, 0);
// Filter positives and square them
List<Integer> result = [Link]()
.filter(x -> x > 0)
.map(x -> x * x)
.collect([Link]());
[Link](result); // [9, 16]
}
}
Explanation: We build a stream from nums , apply filter and map , and collect results. Concept: fluent
stream operations (Java 8+).
19
[Link](name + " rising after " + [Link] + "
bowed.");
}
}
public static void main(String[] args) {
final Friend a = new Friend("Alice");
final Friend b = new Friend("Bob");
// Thread 1: Alice bows to Bob
new Thread(() -> [Link](b)).start();
// Thread 2: Bob bows to Alice (simultaneously)
new Thread(() -> [Link](a)).start();
// Possible deadlock: each thread holds one lock and waits on the other.
}
}
import [Link].*;
public class ProducerConsumerDemo {
public static void main(String[] args) {
BlockingQueue<Integer> buffer = new ArrayBlockingQueue<>(5);
// Producer
Runnable producer = () -> {
for(int i = 1; i <= 5; i++) {
try {
[Link](i);
[Link]("Produced " + i);
} catch (InterruptedException e) {
[Link]().interrupt(); }
}
};
// Consumer
Runnable consumer = () -> {
for(int i = 1; i <= 5; i++) {
try {
int val = [Link]();
[Link]("Consumed " + val);
} catch (InterruptedException e) {
[Link]().interrupt(); }
}
};
new Thread(producer).start();
20
new Thread(consumer).start();
}
}
Explanation: We use a BlockingQueue to safely pass data between producer/consumer threads. This
avoids explicit wait/notify. Concept: thread-safe buffer (Java 8+ [Link] ).
import [Link].*;
public class ReadFileExample {
public static void main(String[] args) {
// Suppose "[Link]" exists in working directory
try (BufferedReader reader = new BufferedReader(new
FileReader("[Link]"))) {
String line;
while ((line = [Link]()) != null) {
[Link](line);
}
} catch (IOException e) {
[Link]();
}
}
}
Explanation: Uses BufferedReader in a try-with-resources to auto-close. Concept: classic I/O for text files.
import [Link].*;
// A sample serializable class
class Person implements Serializable {
private String name;
public Person(String n) { name = n; }
public String toString() { return "Person{name='" + name + "'}"; }
}
public class SerializationDemo {
public static void main(String[] args) {
Person p = new Person("Alice");
// Serialize
try (ObjectOutputStream oos = new ObjectOutputStream(new
FileOutputStream("[Link]"))) {
[Link](p);
} catch (IOException e) { [Link](); }
// Deserialize
21
try (ObjectInputStream ois = new ObjectInputStream(new
FileInputStream("[Link]"))) {
Person p2 = (Person) [Link]();
[Link](p2); // Person{name='Alice'}
} catch (IOException | ClassNotFoundException e) {
[Link](); }
}
}
Explanation: We write the Person object to a file via ObjectOutputStream and read it back. Concept:
Java serialization (make class implement Serializable ).
22
Recommended Resources
• Oracle Java Documentation & Tutorials – Official guides on language features and libraries (e.g.
Java™ Tutorials on Collections, Streams, etc.)【26†L73-L80】【19†L74-L77】.
• OpenJDK Project – Source code and updates for the Java platform ([Link]).
• Effective Java (Joshua Bloch) – Widely cited best practices for Java (a top Java book)【30†L61-L69】.
• LeetCode – Extensive collection of coding problems and discussions (widely used for interview prep)
【32†L1-L2】.
• GeeksforGeeks – Large repository of articles and practice problems on Java and algorithms
【34†L29-L32】.
Each question above tests a core concept: for instance, many string problems use StringBuilder (since
String is immutable【27†L1-L3】), sorting tasks rely on [Link]() , and concurrency questions
emphasize thread coordination. By practicing these questions and understanding the outlined hints, you
should build strong Java interview readiness.
23