Java Interview QnA (Part-2)
These questions delve into core and advanced Java concepts that are not only frequently asked in interviews but are also critical for solving real-world challenges in project development
** Checkout the first set of 10 Questions in the previous article here — https://medium.com/@arvind4gl/java-interview-qna-part-1-f9c4698e8eb1
1. What is the java.util.stream
API, and how does it differ from collections?
The Stream API in Java 8 facilitates functional-style operations on sequences of elements, such as filtering, mapping, and reducing. Unlike collections:
- Streams are lazy: Operations are evaluated only when needed.
- Streams are not data structures: They process data from sources (e.g., collections, arrays).
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5);
int sum = numbers.stream()
.filter(n -> n % 2 == 0)
.mapToInt(Integer::intValue)
.sum();
System.out.println(sum); // Output: 6
2. How is synchronized
different from ReentrantLock
?
synchronized
:
- Simpler, implicit locking.
- Cannot specify lock fairness or timeout.
ReentrantLock
:
- Explicit locking, more flexible.
- Supports tryLock() and interruptible locks.
ReentrantLock lock = new ReentrantLock();
lock.lock();
try {
// Critical section
} finally {
lock.unlock();
}
3. What are daemon threads, and how do they work?
Daemon threads are low-priority threads that run in the background for supporting tasks (e.g., garbage collection). They terminate automatically when all user threads finish execution.
Thread daemonThread = new Thread(() -> System.out.println("Daemon running"));
daemonThread.setDaemon(true);
daemonThread.start();
4. Explain try-with-resources
and its advantages.
Introduced in Java 7, it ensures automatic resource management (e.g., closing streams) by implementing the AutoCloseable
interface.
try (BufferedReader br = new BufferedReader(new FileReader("file.txt"))) {
System.out.println(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
Advantages: No need for explicit finally
blocks to close resources.
5. How does Java implement method references and what are their types?
Method references are shorthand for lambda expressions that call a specific method.
Types:
- Reference to a static method (
ClassName::staticMethod
). - Reference to an instance method of a particular object (
object::instanceMethod
). - Reference to an instance method of an arbitrary object (
ClassName::instanceMethod
). - Reference to a constructor (
ClassName::new
).
List<String> names = Arrays.asList("Alice", "Bob", "Charlie");
names.forEach(System.out::println); // Instance method reference
6. Explain enum
in Java and how it can be used.
Enums are special classes to define constants. They can include fields, methods, and constructors.
enum Day {
MONDAY, TUESDAY, WEDNESDAY;
public boolean isWeekend() { return this == SATURDAY || this == SUNDAY; }
}
System.out.println(Day.MONDAY.isWeekend()); // Output: false
7. What is Java’s Fork/Join
framework, and when should you use it?
The Fork/Join
framework (Java 7) is designed for parallel processing by dividing a task into smaller subtasks (fork) and combining results (join). Ideal for recursive, large, and independent tasks.
class SumTask extends RecursiveTask<Integer> {
int[] array; int start, end;
public SumTask(int[] array, int start, int end) { /* init */ }
@Override protected Integer compute() {
if (end - start <= 10) return Arrays.stream(array, start, end).sum();
int mid = (start + end) / 2;
SumTask left = new SumTask(array, start, mid);
SumTask right = new SumTask(array, mid, end);
left.fork();
return right.compute() + left.join();
}
}
8. What are soft, weak, and phantom references in Java?
- SoftReference: Retained until memory is needed.
- WeakReference: Cleared during the next GC cycle if no strong references exist.
- PhantomReference: Used for cleanup after an object is finalized.
WeakReference<String> weakRef = new WeakReference<>(new String("Weak"));
System.out.println(weakRef.get()); // Can return null if GC occurred
9. Explain the Pattern
and Matcher
classes in Java for regex operations.
Pattern
: Represents a compiled regex.Matcher
: Provides regex operations like matching, finding, and replacing.
Pattern pattern = Pattern.compile("\\d+");
Matcher matcher = pattern.matcher("abc123def456");
while (matcher.find()) {
System.out.println(matcher.group()); // Output: 123, then 456
}
10. How does ThreadLocal
work, and when should you use it?
ThreadLocal
provides thread-specific storage. Each thread accessing a ThreadLocal
gets an independent value.
Use case: Storing user session data in multi-threaded environments.
ThreadLocal<Integer> threadLocal = ThreadLocal.withInitial(() -> 0);
threadLocal.set(threadLocal.get() + 1);
System.out.println(threadLocal.get()); // Value specific to current thread
— — — — -
Let me know your thoughts/feedback in the comment section. Clap this story if found useful and follow me for more such content.
If you want to deep dive to any of the question above let me know in the comment, i can plan to create the dedicated video for that too.
** Checkout the first set of 10 Questions in the previous article here — https://medium.com/@arvind4gl/java-interview-qna-part-1-f9c4698e8eb1