Test your Java knowledge with 20 real interview questions covering OOP, Collections, Streams, Multithreading, Exception Handling, Generics, Memory Management, and String handling. Perfect for preparing for your next Java developer interview.
Below are all 20 questions covered in this quiz, grouped by topic. Each question includes the correct answer and a detailed explanation to help you prepare for your next interview.
What is the output of the following code?
String s1 = "hello";
String s2 = "hello";
String s3 = new String("hello");
System.out.println(s1 == s2);
System.out.println(s1 == s3);true, false
String literals are interned in the String Pool, so s1 and s2 reference the same object (s1 == s2 is true). However, new String("hello") creates a new object on the heap, so s1 == s3 is false because == compares references, not values.
Why is the String class immutable in Java?
All of the above — security, caching, thread-safety, and performance
String is immutable for multiple reasons: security (strings are used in class loading, network connections, and database URLs), thread-safety (immutable objects are inherently thread-safe), caching (the String Pool relies on immutability), and it allows safe use as HashMap keys.
Which of the following is NOT a principle of Object-Oriented Programming?
Compilation
The four pillars of OOP are Encapsulation, Inheritance, Polymorphism, and Abstraction. Compilation is a language processing step, not an OOP principle.
What happens if you don't override hashCode() when you override equals()?
Objects that are equal may not work correctly in hash-based collections like HashMap and HashSet
The contract states that if two objects are equal (equals() returns true), they must have the same hashCode(). If you override equals() without hashCode(), equal objects may hash to different buckets in HashMap/HashSet, causing lookups to fail.
What happens when you call HashMap.put() with a key that already exists in the map?
It replaces the old value with the new value and returns the old value
When a duplicate key is inserted into a HashMap, the old value is replaced by the new value, and the put() method returns the previous value associated with that key (or null if there was none).
What is the difference between ArrayList and LinkedList in terms of performance?
ArrayList is faster for random access; LinkedList is faster for insertions/deletions in the middle
ArrayList uses a dynamic array internally, giving O(1) random access but O(n) for insertions/deletions in the middle. LinkedList uses a doubly-linked list, making insertions/deletions O(1) if you have a reference to the node, but O(n) for random access.
What is the difference between Comparable and Comparator interfaces?
Comparable defines natural ordering within the class; Comparator defines external ordering
Comparable is implemented by the class itself to define its natural ordering (via compareTo()). Comparator is a separate class/lambda that defines an external comparison strategy (via compare()), allowing multiple sort orders without modifying the original class.
What will this stream operation return?
List.of(1, 2, 3, 4, 5).stream()
.filter(n -> n % 2 == 0)
.map(n -> n * n)
.collect(Collectors.toList());[4, 16]
The stream first filters for even numbers (2, 4), then maps each to its square (4, 16). The result is [4, 16].
What is the difference between Stream.map() and Stream.flatMap()?
map() transforms each element; flatMap() transforms and flattens nested streams into a single stream
map() applies a function to each element, producing a 1-to-1 mapping. flatMap() applies a function that returns a stream for each element, then flattens all the resulting streams into a single stream. Useful for one-to-many transformations.
What will Optional.of(null) do in Java?
Throw a NullPointerException
Optional.of(null) throws a NullPointerException immediately. Use Optional.ofNullable(null) if the value might be null — it returns Optional.empty() in that case.
Which statement about Java's synchronized keyword is correct?
It ensures that only one thread can execute the synchronized code at a time for the same monitor
The synchronized keyword ensures mutual exclusion: only one thread can hold the monitor (lock) at a time. It can be applied to methods or code blocks. It does not make variables volatile, nor does it prevent deadlocks.
Which of the following creates a deadlock scenario?
Two threads each holding a lock the other needs, waiting indefinitely
A deadlock occurs when two or more threads are blocked forever, each waiting for a lock held by the other. A single thread can acquire the same reentrant lock multiple times without deadlock. Volatile variables don't cause deadlocks.
What does the volatile keyword guarantee in Java?
That reads and writes to the variable are always done directly to main memory, ensuring visibility across threads
The volatile keyword guarantees visibility: every read of a volatile variable will see the most recent write by any thread. However, it does NOT guarantee atomicity for compound operations like i++ (use AtomicInteger or synchronization for that).
What is the purpose of the finally block in a try-catch-finally statement?
It always executes regardless of whether an exception was thrown or caught
The finally block always executes after the try and catch blocks, regardless of whether an exception was thrown, caught, or not. The only exception is if System.exit() is called or the JVM crashes.
What is the difference between checked and unchecked exceptions in Java?
Checked exceptions must be caught or declared; unchecked exceptions (RuntimeException subclasses) don't require explicit handling
Checked exceptions (subclasses of Exception but not RuntimeException) must be declared in the throws clause or caught in a try-catch block. Unchecked exceptions (subclasses of RuntimeException) don't require explicit handling by the compiler.
What is type erasure in Java Generics?
The compiler removes generic type information during compilation, replacing it with bounds or Object
Type erasure is the process by which the Java compiler removes all generic type information during compilation. Generic types are replaced with their bounds (or Object if unbounded). This is why you cannot use instanceof with generic types or create generic arrays.
What does List<? super Integer> mean in Java Generics?
A list of Integer or any supertype of Integer (Number, Object)
The ? super Integer is a lower-bounded wildcard. It means the list can be of type Integer, Number, or Object. This follows the PECS principle (Producer Extends, Consumer Super) — use super when you want to write/add items to the collection.
In Java's memory model, where are objects stored?
Heap memory
Objects in Java are stored in heap memory. The stack stores local variables and method call frames, including references to heap objects. The method area stores class-level data like static variables and method bytecode.
What is the purpose of the transient keyword in Java?
It prevents a field from being serialized
The transient keyword marks a field to be excluded from serialization. When an object is serialized, transient fields are not saved. This is useful for sensitive data like passwords or for fields that can be derived from other data.
Which Java Garbage Collector is best suited for low-latency applications requiring minimal pause times?
ZGC (Z Garbage Collector)
ZGC is designed for low-latency applications, with pause times typically under 10ms regardless of heap size. Serial GC is single-threaded, Parallel GC focuses on throughput, and CMS is deprecated since Java 14.
Take the interactive quiz and get your score with a personalized topic breakdown.
Start the Quiz20 questions · 30 min
Java20 questions · 30 min
Java20 questions · 30 min
Java20 questions · 30 min
Java20 questions · 30 min
Spring Boot20 questions · 30 min
Spring Boot20 questions · 30 min
Spring Boot20 questions · 30 min
Spring Boot20 questions · 30 min
Spring Boot20 questions · 30 min
Spring Boot20 questions · 30 min
DevOps20 questions · 30 min
Join thousands of developers mastering in-demand skills with Amigoscode. Try it free today.