Skip to primary content
Java Technical Prep

Enterprise Java Interview Questions & Answers

Crack technical Java interviews. In-depth answers with code, real scenarios, JVM internals, memory allocation, collections, and common mistakes.

Question 1

Why is String immutable in Java, and how does the String Constant Pool function?

In Java, String objects cannot be modified once instantiated. Any operation that appears to mutate a String creates a new object in memory.

String immutability provides three critical advantages: 1) Security: Strings are widely used to store sensitive network connections, passwords, and file paths; mutable strings could be altered maliciously across threads. 2) Synchronization: Immutable strings are inherently thread-safe without explicit synchronization. 3) Caching: Immutability enables the JVM to maintain the String Constant Pool (SCP) in heap memory, reusing identical string literals to dramatically reduce memory footprint.

Java
String s1 = "Ghaziabad";
String s2 = "Ghaziabad";
System.out.println(s1 == s2); // true: Points to identical object in SCP

String s3 = new String("Ghaziabad");
System.out.println(s1 == s3); // false: New object on regular heap
System.out.println(s1.equals(s3)); // true: Value comparison

In a high-throughput payment gateway processing millions of order requests, passing order IDs as immutable Strings ensures no background thread can tamper with the transaction reference during database verification.

Interviewer Pro Tip: When an interviewer asks about String immutability, always mention how String caches its hashCode() on first computation, making it the ideal key in HashMaps.
Common Candidate Mistake: Using regular String concatenation (+) inside loops instead of StringBuilder, which creates thousands of discarded intermediate String objects and burdens the Garbage Collector.

Related follow-up question: What is the difference between String, StringBuilder, and StringBuffer?

Question 2

What is the difference between fail-fast and fail-safe iterators in Java Collections?

Iterators traverse collections and respond differently when the collection is structurally modified during iteration.

Fail-fast iterators (e.g. ArrayList, HashMap) immediately throw ConcurrentModificationException if the underlying collection is modified structurally (adding or removing elements) by any means other than the iterator own remove() method. They detect this using an internal modCount flag. Fail-safe (or weakly consistent) iterators (e.g. CopyOnWriteArrayList, ConcurrentHashMap) traverse a snapshot of the collection or tolerate concurrent modifications without throwing an exception.

Java
List<String> list = new ArrayList<>(List.of("A", "B", "C"));
for (String item : list) {
    if (item.equals("B")) {
        // Throws ConcurrentModificationException!
        list.remove(item);
    }
}

// Correct approach using Iterator
Iterator<String> it = list.iterator();
while (it.hasNext()) {
    if (it.next().equals("B")) {
        it.remove(); // Safe and supported
    }
}

In an active high-throughput messaging server, broadcasting telemetry to connected clients while new clients connect requires fail-safe collections like CopyOnWriteArrayList to avoid crashes during write cycles.

Interviewer Pro Tip: Mention that fail-safe iterators trade off memory consumption because CopyOnWrite collections copy the entire underlying array on every write operation.
Common Candidate Mistake: Assuming that fail-fast iterators guarantee thread-safety. Fail-fast is only a best-effort bug detection mechanism, not a concurrency synchronization strategy.

Related follow-up question: How does ConcurrentHashMap achieve high concurrency without locking the entire table?

Question 3

How do Java 21 Virtual Threads differ from traditional Platform Threads?

Project Loom introduced Virtual Threads to decouple Java threads from OS kernel threads.

Traditional Platform Threads wrap a 1:1 underlying operating system kernel thread, consuming approximately 1MB of stack memory and requiring expensive kernel context switches. The JVM is typically limited to thousands of platform threads. Virtual Threads (Java 21) are lightweight user-mode threads managed entirely by the JVM. Millions of virtual threads can run concurrently; when a virtual thread performs blocking I/O (like an HTTP call or database query), the JVM unmounts it from its carrier OS thread, allowing other virtual threads to execute.

Java
// Spawning 10,000 concurrent Virtual Threads effortlessly
try (var executor = Executors.newVirtualThreadPerTaskExecutor()) {
    for (int i = 0; i < 10_000; i++) {
        final int taskId = i;
        executor.submit(() -> {
            Thread.sleep(100); // Non-blocking unmount on Virtual Thread
            return "Task " + taskId + " completed";
        });
    }
} // Automatically awaits completion

A microservice handling thousands of simultaneous incoming REST calls waiting on downstream third-party database calls can adopt Virtual Threads to achieve immense throughput without rewriting code into complex reactive streams.

Interviewer Pro Tip: Highlight that Virtual Threads are designed for I/O-bound tasks, not CPU-bound number crunching where carrier threads remain pegged.
Common Candidate Mistake: Pooling Virtual Threads using thread pools. Virtual Threads should never be pooled; they are cheap to create and should be instantiated per task.

Related follow-up question: What is thread pinning in Java Virtual Threads?

Mock Technical Interviews in Ghaziabad

Prepare for tier-1 company coding and system design rounds with face-to-face mock interview practice at C-60 R.K Tower, 3rd Floor, RDC, Ghaziabad.

Call 7503962162
Physical Training Center

Visit Our Ghaziabad Training Center

Join classroom batches, attend interactive lab sessions, code with mentors, and take advantage of our high-speed dev workstations.

Campus Address:
C-60 R.K Tower, 3rd Floor, RDC, Ghaziabad, Ghaziabad, Uttar Pradesh
Direct Counseling Helpline:
Call 7503962162
Get Google Maps Directions Call Now: 7503962162 Explore Ghaziabad Training Hub
Call 7503962162 Get Course Details