Skip to content

Enterprise · updated 26 November 2026

Java powers large back ends and Android. These scenarios cover collections, memory, concurrency and the JVM.

Top 10 Java scenario questions

Try each one yourself first, then open the model answer.

1. Objects used as HashMap keys cannot be found again. What is the likely cause?

Show answer

equals and hashCode are not overridden consistently, or the key's fields changed after insertion. Equal objects must have equal hash codes, and keys should be immutable.

2. The service throws OutOfMemoryError after a few days. How do you investigate?

Show answer

Capture a heap dump, for example with the HeapDumpOnOutOfMemoryError option, and analyse what retains memory. Common causes are unbounded caches, static collections and listeners that are never removed.

3. Two threads increment a shared counter and the total is wrong. How would you fix it?

Show answer

count++ is not atomic. Use AtomicInteger or LongAdder, or guard it with a lock. volatile alone gives visibility, not atomicity.

4. Your application deadlocks occasionally. How do you find and prevent it?

Show answer

Take a thread dump with jstack, which reports lock cycles. Prevent deadlocks by acquiring locks in a consistent order, holding them briefly, or using tryLock with a timeout.

5. You get ConcurrentModificationException while removing items in a loop. What do you do?

Show answer

Use the iterator's remove method or removeIf. For access from several threads use a concurrent collection.

6. A loop that builds a report by adding to a String is very slow. Why?

Show answer

Strings are immutable, so each concatenation in the loop creates a new object. Use StringBuilder.

7. Thousands of requests wait on slow database calls and threads run out. What are your options?

Show answer

Use a bounded connection pool with timeouts, optimise the queries, and consider virtual threads (Java 21) or non-blocking I/O so waiting does not tie up platform threads.

8. A method returns null and callers keep hitting NullPointerException. How would you redesign it?

Show answer

Return an empty collection for lists, use Optional for a return value that may be absent, and validate parameters early with Objects.requireNonNull.

9. Long garbage collection pauses hurt response times. What would you do?

Show answer

Enable GC logging first, then check allocation rate and heap size. Choose a collector suited to latency such as G1 or ZGC, and reduce unnecessary object creation.

10. A file or socket is not closed when an exception occurs. What is the clean solution?

Show answer

Use try-with-resources with AutoCloseable types, which closes resources in reverse order even when exceptions are thrown.

Ready to build something great?

Book your free 30-minute consultation today. No obligation, just honest advice.