HireHireInterview Quizzes › Java Developer

Java Developer Interview Questions

Think you're ready? These are the questions that actually decide Java Developer interviews. Warm up on Easy — then face the Hard round, where 95% of candidates crumble. 80 questions across 3 levels, instant score, completely free.

80Questions
3Difficulty levels
95%Fail the hard round
FreeInstant score
Easy
Warm-up · 20 Qs
Medium
Practical · 30 Qs
Hard
Brutal · 30 Qs
⚡ Take the Java Developer quiz — get your score →

The Java Developer interview questions

Below are the real questions, grouped by difficulty. Expand any one to reveal the correct answer and why — or take the timed quiz for a score you can share. Can you clear the Hard round?

Easy round 20 questions

What is printed by: System.out.println(10 + 20 + "30");
  • A. 3030 ✓
  • B. 102030
  • C. Compile error
  • D. 60
Correct answer: A. Left-to-right: 10+20 evaluates to integer 30, then concatenated with "30" gives "3030".
Given String s = "hi"; s.concat("there"); System.out.println(s); what prints?
  • A. hithere
  • B. hi ✓
  • C. there
  • D. hi there
Correct answer: B. Strings are immutable; concat returns a new String that is discarded, so s stays "hi".
What happens when you compare two separate Integer objects both holding 1000 using ==?
  • A. Always true
  • B. false, because == compares references not values ✓
  • C. true, both operands are unboxed to int and compared by value
  • D. false only when using the new Integer(1000) constructor
Correct answer: B. Values above 127 fall outside the Integer cache, so each is a distinct object and == compares references.
Which statement correctly overrides equals() and honors its contract?
  • A. Override equals() but leave hashCode() unchanged
  • B. Override both equals() and hashCode() consistently ✓
  • C. Override hashCode() only
  • D. Override compareTo() instead
Correct answer: B. Equal objects must have equal hash codes, so equals() and hashCode() must be overridden together.
What will happen at runtime: List<String> list = new ArrayList<>(); list.add("a"); for (String s : list) list.remove(s);
  • A. Removes all elements cleanly
  • B. Throws ConcurrentModificationException ✓
  • C. Compile error
  • D. Infinite loop
Correct answer: B. Structurally modifying a list during enhanced-for iteration triggers ConcurrentModificationException from the iterator.
If a method declares a checked exception like IOException, what must the caller do?
  • A. Nothing, it is optional
  • B. Catch it or declare it with throws ✓
  • C. Convert it to RuntimeException
  • D. Wrap the call in a finally block
Correct answer: B. Checked exceptions must be either caught or propagated via a throws clause; the compiler enforces this.
What does the finally block guarantee in a try-catch-finally?
  • A. It runs only if no exception occurs
  • B. It runs only if an exception occurs
  • C. It runs whether or not an exception is thrown ✓
  • D. It replaces the catch block
Correct answer: C. finally executes after try/catch regardless of whether an exception was thrown or caught.
Given int[] a = new int[3]; what is the value of a[0]?
  • A. 0 ✓
  • B. null
  • C. Undefined garbage
  • D. Compile error
Correct answer: A. Array elements of type int are default-initialized to 0 when the array is created.
Which collection should you choose when you need to store unique elements with no duplicates?
  • A. ArrayList
  • B. HashSet ✓
  • C. LinkedList
  • D. PriorityQueue
Correct answer: B. HashSet enforces uniqueness by rejecting duplicate elements based on equals/hashCode.
What is the result of dividing 7 / 2 in Java where both operands are int?
  • A. 3.5
  • B. 3 ✓
  • C. 4
  • D. Compile error
Correct answer: B. Integer division truncates the fractional part, so 7/2 yields 3.
Why can't you store an int directly as the key type in a Map declaration like Map<int, String>?
  • A. Primitives have no hashCode(), which map keys require
  • B. Generics require reference types, so you use Integer ✓
  • C. Maps don't allow numeric keys
  • D. int keys must be final
Correct answer: B. Java generics work only with reference types; you must use the wrapper class Integer, not the primitive int.
What does calling start() on a Thread do compared to calling run() directly?
  • A. Both create a new thread
  • B. start() creates a new thread; run() executes in the current thread ✓
  • C. run() creates a new thread; start() does not
  • D. Neither starts a thread
Correct answer: B. start() spawns a new thread of execution, while run() called directly just runs synchronously in the current thread.
Given the ternary: int x = (5 > 3) ? 1 : 0; what is x?
  • A. 0
  • B. 1 ✓
  • C. 5
  • D. 3
Correct answer: B. 5 > 3 is true, so the ternary evaluates to the first branch, 1.
What is the output of: StringBuilder sb = new StringBuilder("ab"); sb.append("c"); System.out.println(sb);
  • A. ab
  • B. abc ✓
  • C. c
  • D. ab c
Correct answer: B. StringBuilder is mutable and append modifies it in place, producing "abc".
When you declare a variable as final, what does it prevent?
  • A. Reassignment of the variable after initialization ✓
  • B. Modifying the object's fields
  • C. The class from being subclassed
  • D. The method from being overridden
Correct answer: A. final on a variable prevents reassigning it; the referenced object's internal state can still change.
What happens if a switch case does not include a break statement?
  • A. Compile error
  • B. Execution falls through to the next case ✓
  • C. The switch exits immediately
  • D. Only the matching case runs
Correct answer: B. Without break, control falls through and executes subsequent case bodies until a break or the end.
Which access modifier makes a member visible only within the same class?
  • A. protected
  • B. default (package-private)
  • C. private ✓
  • D. public
Correct answer: C. private restricts access to within the declaring class only.
What does the following print: Object o = "hello"; System.out.println(o instanceof String);
  • A. true ✓
  • B. false
  • C. Compile error
  • D. null
Correct answer: A. The runtime type of o is String, so instanceof String evaluates to true.
In a HashMap, what happens when you put a value with a key that already exists?
  • A. Throws an exception
  • B. Adds a second entry with the same key
  • C. Replaces the old value and returns it ✓
  • D. Ignores the new value
Correct answer: C. put() with an existing key overwrites the associated value and returns the previous value.
What is autoboxing in the context of: Integer i = 5;
  • A. Casting Integer to int
  • B. Automatic conversion of int primitive to Integer object ✓
  • C. Creating a new int array
  • D. Converting String to Integer
Correct answer: B. Autoboxing automatically wraps the primitive int 5 into an Integer object.

Medium round 30 questions

You have a List<String> and want to remove all elements equal to "x" while iterating. Which approach avoids a ConcurrentModificationException?
  • A. Loop with an enhanced for-each and call list.remove("x") inside
  • B. Use list.removeIf(s -> s.equals("x")) ✓
  • C. Iterate by index from 0 upward and remove matching elements
  • D. Stream the list and call forEach with list.remove inside
Correct answer: B. removeIf safely removes matching elements without a ConcurrentModificationException, unlike modifying a list during for-each iteration.
What does the following print? String a = "hi"; String b = new String("hi"); System.out.println(a == b);
  • A. true
  • B. false ✓
  • C. It throws a NullPointerException
  • D. It does not compile
Correct answer: B. new String() creates a distinct object on the heap, so == compares references and returns false even though the contents are equal.
In a Spring Boot application, which annotation is most appropriate for a class that holds business logic and should be injected into controllers?
  • A. @Component on a plain class only
  • B. @Service ✓
  • C. @Repository
  • D. @Controller
Correct answer: B. @Service is the semantic stereotype for a business-logic bean, making it discoverable for dependency injection into controllers.
You override equals() in a class used as a HashMap key but forget to override hashCode(). What is the most likely consequence?
  • A. Compilation fails because both must be overridden together
  • B. Lookups may fail to find entries even when an equal key exists ✓
  • C. Every key collides into a single bucket, but lookups still work
  • D. hashCode() is automatically generated to match equals()
Correct answer: B. Unequal hashCodes for equal objects can route them to different buckets, so the map may not find an entry with an equal key.
Which statement about a try-with-resources block is correct?
  • A. It requires an explicit finally block to close the resource
  • B. The resource must implement AutoCloseable and is closed automatically ✓
  • C. It suppresses all exceptions thrown inside the block
  • D. Resources are closed in the same order they were declared
Correct answer: B. try-with-resources closes any resource implementing AutoCloseable automatically, in reverse order of declaration, without a manual finally.
What is the result of Integer.valueOf(127) == Integer.valueOf(127) compared to Integer.valueOf(128) == Integer.valueOf(128)?
  • A. Both are true
  • B. Both are false
  • C. The first is true, the second is false ✓
  • D. The first is false, the second is true
Correct answer: C. Integer caches boxed values from -128 to 127, so 127 returns the same cached reference (true) while 128 creates new objects (false).
In JPA/Hibernate, you load a list of orders and access each order's lazy-loaded items in a loop, firing one query per order. What is this problem called?
  • A. Cartesian product explosion
  • B. The N+1 select problem ✓
  • C. Dirty read anomaly
  • D. Connection pool starvation
Correct answer: B. Executing one additional query per parent entity to fetch its children is the classic N+1 select problem, typically solved with a join fetch.
Which Maven command compiles the project, runs tests, and installs the artifact into your local repository?
  • A. mvn compile
  • B. mvn package
  • C. mvn install ✓
  • D. mvn deploy
Correct answer: C. mvn install runs all lifecycle phases up to and including install, which places the built artifact in the local ~/.m2 repository.
You want a thread-safe counter incremented by many threads without using synchronized blocks. Which is the best fit?
  • A. A volatile int field
  • B. An AtomicInteger ✓
  • C. A plain long field
  • D. A HashMap<String, Integer>
Correct answer: B. AtomicInteger provides lock-free atomic increment via incrementAndGet(), whereas volatile alone does not make the read-modify-write of ++ atomic.
Given a stream of employees, which collector groups them into a Map keyed by department?
  • A. Collectors.toMap(Employee::getDept, e -> e)
  • B. Collectors.groupingBy(Employee::getDept) ✓
  • C. Collectors.partitioningBy(Employee::getDept)
  • D. Collectors.mapping(Employee::getDept, Collectors.toList())
Correct answer: B. Collectors.groupingBy produces a Map<Dept, List<Employee>> grouping elements by the classifier, which is exactly what is needed here.
For heavy string concatenation inside a single-threaded loop, which is most efficient?
  • A. String
  • B. StringBuffer
  • C. StringBuilder ✓
  • D. char array
Correct answer: C. StringBuilder is mutable and unsynchronized, ideal for single-threaded concatenation.
How many null keys can a standard HashMap contain?
  • A. 0
  • B. 1 ✓
  • C. Unlimited
  • D. It throws on a null key
Correct answer: B. HashMap permits exactly one null key.
A resource used in a try-with-resources statement must implement which interface?
  • A. Closeable only
  • B. AutoCloseable ✓
  • C. Serializable
  • D. Runnable
Correct answer: B. try-with-resources requires AutoCloseable (Closeable extends it).
If both the try block and the finally block execute a return, which value is returned?
  • A. The try block's value
  • B. The finally block's value ✓
  • C. A compile error occurs
  • D. The method returns twice
Correct answer: B. A return in finally overrides any return from try.
Method overloading is resolved at which point?
  • A. Compile time ✓
  • B. Runtime
  • C. Class-load time
  • D. During JIT compilation
Correct answer: A. Overload resolution is static, decided by the compiler from the declared argument types.
For which list is get(index) an O(1) operation?
  • A. LinkedList
  • B. ArrayList ✓
  • C. Both equally
  • D. Neither
Correct answer: B. ArrayList is backed by an array giving constant-time indexed access.
To define a class's natural ordering within the class itself, which interface do you implement?
  • A. Comparator
  • B. Comparable ✓
  • C. Iterable
  • D. Cloneable
Correct answer: B. Comparable's compareTo defines a type's natural ordering.
A static method can directly access which of the following?
  • A. Instance fields of the class
  • B. Only static members directly ✓
  • C. The this reference
  • D. Overridden instance methods
Correct answer: B. Static methods have no instance context, so they can reference only static members directly.
Per the equals/hashCode contract, if two objects are equal their hashCodes must be?
  • A. Different
  • B. Equal ✓
  • C. Both zero
  • D. Both positive
Correct answer: B. Equal objects are required to return equal hashCode values.
Java generics are implemented at compile time using which mechanism?
  • A. Reification
  • B. Type erasure ✓
  • C. C++-style templates
  • D. Autoboxing
Correct answer: B. Generic type information is erased at compile time, leaving raw types at runtime.
What does System.out.println(0.1 + 0.2 == 0.3) print?
  • A. true
  • B. false ✓
  • C. compile error
  • D. runtime exception
Correct answer: B. Binary floating-point rounding makes 0.1 + 0.2 slightly larger than 0.3, so the comparison is false.
What does the transient keyword do to a field?
  • A. Makes the field thread-safe
  • B. Excludes the field from serialization ✓
  • C. Prevents the field from being inherited
  • D. Marks it as a temporary local variable
Correct answer: B. transient fields are skipped by Java's default serialization mechanism.
Which statement about String in Java is true?
  • A. Strings can be modified in place
  • B. Strings are always stored on the stack
  • C. Strings are immutable ✓
  • D. == compares String content
Correct answer: C. String objects are immutable; any modification produces a new String.
What happens if you call list.add() while iterating an ArrayList with an enhanced for loop?
  • A. NullPointerException
  • B. IndexOutOfBoundsException
  • C. ConcurrentModificationException ✓
  • D. It silently succeeds
Correct answer: C. The iterator detects structural modification via modCount and throws ConcurrentModificationException.
How do == and equals() differ for object references by default?
  • A. Both compare content
  • B. == compares references, equals() compares content (when overridden) ✓
  • C. Both compare references
  • D. equals() compares references, == compares content
Correct answer: B. == tests reference identity, while a properly overridden equals() compares logical content.
How does HashMap handle a null key?
  • A. Disallows null keys
  • B. Allows multiple null keys
  • C. Allows exactly one null key ✓
  • D. Throws NPE on a null key
Correct answer: C. HashMap permits a single null key (stored in bucket 0); Hashtable/ConcurrentHashMap do not.
What does the volatile keyword guarantee?
  • A. Atomicity of compound operations
  • B. Mutual exclusion
  • C. Visibility of writes across threads ✓
  • D. Ordering of all program operations
Correct answer: C. volatile ensures visibility (and a memory barrier) but not atomicity of read-modify-write operations.
Which pattern is a common source of memory leaks in Java?
  • A. Using try-with-resources
  • B. Retaining references in a long-lived static collection ✓
  • C. Using local variables
  • D. Using StringBuilder
Correct answer: B. Objects held by static collections are never garbage-collected until explicitly removed, causing leaks.
What is autoboxing in Java?
  • A. Automatic conversion between primitives and their wrapper types ✓
  • B. Automatic garbage collection
  • C. Automatic array resizing
  • D. Automatic exception handling
Correct answer: A. Autoboxing automatically converts a primitive (e.g., int) to its wrapper (Integer) and vice versa.
What is the result of Integer.valueOf(127) == Integer.valueOf(127)?
  • A. false
  • B. true ✓
  • C. compile error
  • D. runtime exception
Correct answer: B. Integer caches values from -128 to 127, so both calls return the same cached instance and == is true.

Hard round 30 questions

A team ships a lazy singleton using double-checked locking, but the `instance` field is a plain (non-volatile) `Object`. Under load on a multi-core JVM, another thread occasionally sees a non-null `instance` whose fields are still at their default values. What is the precise root cause?
  • A. The compiler removes the inner null check via lock elision, so two threads run the constructor concurrently
  • B. Without volatile, the write publishing the reference can be reordered before the constructor's field writes complete, so a reader sees a non-null but partially-constructed object ✓
  • C. The synchronized block only guarantees mutual exclusion, so the second thread always re-runs the constructor and overwrites the first instance
  • D. HotSpot never caches object references in registers, so the issue is purely a heap-visibility flush that a memory barrier on read would fix
Correct answer: B. Without volatile there is no happens-before edge, so the reference publication can be reordered ahead of the constructor's writes, exposing a partially-constructed object to another thread.
Consider `private volatile int[] data = new int[10];` accessed by many threads that do `data[i]++` concurrently on distinct-looking but sometimes overlapping indices. Why does marking the array reference `volatile` fail to make these updates thread-safe?
  • A. volatile only establishes visibility/ordering for reads and writes of the reference itself, not for reads/writes of the array's elements, which remain unsynchronized ✓
  • B. volatile arrays are copied on every write, so the increment operates on a stale snapshot
  • C. volatile forces every element access through a lock, but the lock is reentrant so nested increments corrupt the counter
  • D. The JIT strips volatile from array fields during escape analysis, silently downgrading it to a plain field
Correct answer: A. The volatile modifier applies to the reference variable, not the elements; per-element mutations have no memory-model guarantees and the `++` is also non-atomic.
Two threads run this code with shared `int x = 0; boolean ready = false;` — Thread A: `x = 42; ready = true;` — Thread B: `if (ready) System.out.println(x);`. Neither variable is volatile or synchronized. Which statement about permitted outcomes is correct under the JMM?
  • A. B can only ever print 42, because assignment order in A is preserved by program order across threads
  • B. B can print 0 or observe ready==true before x==42, because without a happens-before relation A's writes may be observed out of order ✓
  • C. The program is guaranteed to deadlock since ready is read without a lock
  • D. B will always block until ready becomes true because reads of shared booleans are implicitly synchronized
Correct answer: B. Absent a happens-before edge, Thread B may observe `ready==true` while still reading the stale `x==0` due to permitted reordering/visibility gaps.
You have a producer-consumer using `wait()`/`notify()`. A reviewer insists the consumer's `wait()` must sit inside `while (queue.isEmpty())` rather than `if (queue.isEmpty())`. What is the strongest technical justification?
  • A. `if` would hold the monitor during wait, whereas `while` releases it, preventing a deadlock
  • B. A thread returning from wait may find the condition false again due to spurious wakeups or another consumer having drained the item, so the predicate must be re-checked in a loop ✓
  • C. `notify()` only wakes threads that used `while`, so `if`-based waiters are never scheduled
  • D. `while` guarantees FIFO fairness among waiters, which `if` cannot provide
Correct answer: B. wait() can return without the intended condition holding (spurious wakeups, or another thread consumed the item), so the guard must be re-tested in a loop.
A `@Service` bean has a public `outer()` method (no annotation) that calls `this.inner()`, where `inner()` is annotated `@Transactional(propagation = REQUIRES_NEW)`. At runtime `inner()` runs in no transaction at all. Why?
  • A. REQUIRES_NEW is ignored unless the outer method is also @Transactional, so propagation silently downgrades to SUPPORTS
  • B. The self-invocation `this.inner()` bypasses the Spring CGLIB/JDK proxy, so the transactional advice around inner() never fires ✓
  • C. REQUIRES_NEW requires an XA datasource; without one Spring skips transaction creation and logs a warning
  • D. Spring caches the transaction status per thread, and since outer() opened none, inner() inherits the empty context permanently
Correct answer: B. Transactional advice lives on the proxy; an internal `this.` call goes straight to the target instance, skipping the proxy and thus all propagation handling.
A production service running Hibernate returns a `User` entity from a `@Transactional` service method to a controller, which then accesses `user.getOrders()` (a `LAZY` collection) to render JSON. Users get intermittent `LazyInitializationException`. What is the correct root-cause explanation?
  • A. The collection was mapped EAGER, so Hibernate throws when it detects a redundant fetch in the view layer
  • B. The persistence context/session closed when the transactional method returned, so the proxy has no session to initialize the collection during controller-layer access ✓
  • C. The exception occurs because getOrders() triggers an N+1 query that exceeds the connection pool, timing out the fetch
  • D. Jackson serializes the collection on a different thread that lacks the ThreadLocal session, unlike single-threaded access which succeeds
Correct answer: B. Lazy collections need an open session to initialize; once the transactional boundary closes the session, touching the uninitialized proxy later throws LazyInitializationException.
A REST endpoint calls a downstream payment API. On timeout your client retries. Occasionally a customer is charged twice. Which approach most directly prevents duplicate side effects while keeping at-least-once retry semantics?
  • A. Switch retries to at-most-once by disabling them entirely, accepting occasional lost charges
  • B. Attach a client-generated idempotency key to each logical request so the server deduplicates retries of the same operation ✓
  • C. Wrap the call in a distributed lock so only one node can call the payment API at a time
  • D. Increase the client socket timeout so responses always arrive before a retry is triggered
Correct answer: B. An idempotency key lets the server recognize a retried request as the same logical operation and return the original result instead of charging again.
You must reliably publish an event to Kafka whenever a row is written to your SQL database, but a crash between the DB commit and the Kafka send can lose events (dual-write problem). Which pattern correctly guarantees the event is not lost?
  • A. Send to Kafka first, then commit the DB row, so the broker is the source of truth
  • B. Use the Outbox pattern: write the event into an outbox table in the same DB transaction, then a separate relay reads and publishes it, retrying until acknowledged ✓
  • C. Wrap both the DB commit and the Kafka producer.send() in a single synchronized block
  • D. Enable Kafka idempotent producer, which retroactively rolls back the DB row if the send fails
Correct answer: B. The Outbox pattern makes the event write atomic with the business data (one DB transaction), and a separate relay guarantees at-least-once delivery to Kafka.
A latency-sensitive service (P99 pause budget ~10ms) runs on a 64GB heap and suffers multi-hundred-millisecond stop-the-world pauses during full GCs with the Parallel collector. Which change best fits the requirement, and why?
  • A. Switch to ZGC, because it performs concurrent marking and relocation to keep pauses sub-millisecond largely independent of heap size ✓
  • B. Switch to the Serial collector to reduce GC thread contention on the large heap
  • C. Keep Parallel GC but set -XX:MaxGCPauseMillis=10, which converts full GCs into concurrent cycles
  • D. Shrink the heap to 4GB so full GCs complete within the 10ms budget
Correct answer: A. ZGC is designed for low, near-constant pause times that scale to large heaps by doing marking and relocation concurrently, matching a tight P99 pause goal.
A mutable object is used as a key in a `HashMap`. After insertion, code mutates a field that participates in `equals`/`hashCode`. Later `map.get(sameKeyReference)` returns null even though the entry is clearly present. What is the precise mechanism?
  • A. HashMap rehashes on every mutation, so the entry was moved to a bucket the key no longer maps to
  • B. The entry was stored in the bucket derived from the original hashCode; the mutated key now hashes to a different bucket, so the lookup probes the wrong bucket and misses the entry ✓
  • C. equals() now returns false against itself, so identity comparison inside get() fails
  • D. Treeification converted the bucket to a red-black tree keyed by the old hash, corrupting the lookup index
Correct answer: B. The entry stays in the bucket chosen at insertion time; a mutated hashCode routes get() to a different bucket, so it never finds the entry.
What does the volatile keyword guarantee?
  • A. Atomicity of compound operations like i++
  • B. Visibility of writes to all threads ✓
  • C. Mutual exclusion around the field
  • D. Reordering only within one thread
Correct answer: B. volatile ensures visibility and ordering of reads/writes but not atomicity of compound operations.
Under the standard parent-delegation model, a ClassLoader first attempts to load a class from?
  • A. The current classloader itself
  • B. Its parent classloader ✓
  • C. The bootstrap loader by scanning disk
  • D. The system classpath directly
Correct answer: B. Delegation asks the parent first, and only loads locally if the parent cannot.
How is the heap organized in the G1 garbage collector?
  • A. Contiguous young and old spaces
  • B. Equal-sized regions ✓
  • C. Purely by object age generations
  • D. Thread-local allocation buffers only
Correct answer: B. G1 partitions the heap into many equal-sized regions dynamically assigned roles.
What does String.intern() return?
  • A. A freshly allocated String copy
  • B. The canonical reference from the string pool ✓
  • C. The string's hash code
  • D. An interned char array
Correct answer: B. intern() returns the canonical pooled reference, adding the string if absent.
How does Java 8's ConcurrentHashMap achieve thread safety on writes?
  • A. A single global lock
  • B. Segment locks as in Java 7
  • C. CAS on empty bins plus synchronized on the bin head ✓
  • D. Copy-on-write of the whole table
Correct answer: C. Java 8 uses CAS for empty bins and synchronizes on the first node of a non-empty bin.
For a correct double-checked-locking singleton, the instance field must be declared?
  • A. static only
  • B. final
  • C. volatile ✓
  • D. transient
Correct answer: C. volatile prevents a thread from seeing a partially constructed instance due to reordering.
Which statement about Object.finalize() is correct?
  • A. It runs immediately when the object becomes unreachable
  • B. It is guaranteed to run before JVM exit
  • C. It may never be called at all ✓
  • D. It always runs on the main thread
Correct answer: C. The JVM makes no guarantee that finalize() is ever invoked.
Integer.valueOf caches boxed instances for which value range?
  • A. 0 to 255
  • B. -128 to 127 ✓
  • C. -256 to 255
  • D. No values are cached
Correct answer: B. The Integer cache covers -128 to 127 by default, so == can be true in that range.
What triggers a ConcurrentModificationException from an ArrayList iterator?
  • A. A concurrent read on another thread
  • B. A modCount mismatch detected during iteration ✓
  • C. The presence of null elements
  • D. An internal capacity resize
Correct answer: B. The fail-fast iterator compares an expected modCount against the list's modCount and throws on mismatch.
Which action establishes a happens-before relationship in the Java Memory Model?
  • A. Two unsynchronized reads on different threads
  • B. Unlocking a monitor before a later lock of the same monitor ✓
  • C. Setting a higher thread priority
  • D. Calling System.gc()
Correct answer: B. An unlock happens-before any subsequent lock of the same monitor.
What does the happens-before relationship in the Java Memory Model establish?
  • A. Visibility and ordering guarantees between actions ✓
  • B. Thread priority ordering
  • C. Garbage collection ordering
  • D. Method invocation ordering
Correct answer: A. happens-before defines when one action's memory effects are guaranteed visible and ordered before another's.
What is a well-known hazard of using a plain HashMap concurrently in pre-Java 8 JVMs?
  • A. A guaranteed compile error
  • B. An infinite loop during a concurrent resize/rehash ✓
  • C. A guaranteed deadlock every time
  • D. No issue at all
Correct answer: B. Concurrent resizing could corrupt the linked bucket list into a cycle, causing an infinite loop on get().
In the G1 garbage collector, what is a Region?
  • A. A fixed-size subdivision of the heap ✓
  • B. A pool of worker threads
  • C. A class-loader scope
  • D. A single stack frame
Correct answer: A. G1 partitions the heap into equal fixed-size regions that are dynamically assigned as Eden, Survivor, or Old.
What does Collections.unmodifiableList() return?
  • A. A read-only view that throws on mutation attempts ✓
  • B. A deep copy of the list
  • C. A synchronized list
  • D. A thread-safe concurrent list
Correct answer: A. It returns a wrapper view backed by the original list; mutation throws UnsupportedOperationException but backing changes still show through.
How do return statements in try and finally interact?
  • A. The try block's return always wins
  • B. A return in finally overrides the try block's return ✓
  • C. finally never runs after a return
  • D. It is a compile error
Correct answer: B. A return in finally executes last and suppresses/overrides any return value from the try block.
What does declaring an instance method synchronized do?
  • A. Locks on the instance (this) monitor ✓
  • B. Locks on the Class object
  • C. Acquires a single global JVM lock
  • D. Performs no locking
Correct answer: A. A synchronized instance method acquires the intrinsic lock of the object (this).
Which delegation model does the standard Java ClassLoader hierarchy follow?
  • A. Parent-first delegation ✓
  • B. Child-first delegation
  • C. No delegation
  • D. Random delegation
Correct answer: A. By default a class loader delegates to its parent first before attempting to load a class itself.
What happens if you invoke start() twice on the same Thread object?
  • A. It runs the thread body twice
  • B. It throws IllegalThreadStateException ✓
  • C. It silently does nothing
  • D. It spawns a brand-new thread
Correct answer: B. A Thread can be started only once; a second start() throws IllegalThreadStateException.
What is type erasure in Java generics?
  • A. Generic type information is removed at compile time ✓
  • B. Generics are enforced at runtime
  • C. Types are erased during class loading
  • D. Primitives are automatically boxed
Correct answer: A. The compiler erases generic type parameters to their bounds, so the type info is not retained at runtime.
How do CompletableFuture.thenApply and thenApplyAsync differ?
  • A. Both always run asynchronously
  • B. thenApply may run in the completing thread; thenApplyAsync uses an executor ✓
  • C. Both always run on the main thread
  • D. Both always run in the same fixed thread
Correct answer: B. thenApply may execute in the thread that completed the stage, while thenApplyAsync submits the work to an executor.

Prep for another role

Questions are original, written and independently verified for HireHire's role interview quizzes. They reflect the kind of knowledge Java Developer interviews test, not any specific company's questions. HireHire maps live tech & IT jobs across India, updated regularly. Last updated: August 2026.