Interview Q&A / Java
Java interview questions
Collections, the JVM, strings, exceptions and threads, the backbone of most campus placement rounds.
Prefer rapid revision? Practise Java short interview answers →
- How does a deadlock happen in Java and how can you avoid it?
A deadlock occurs when threads each hold one lock and wait forever for a lock the other holds. Avoid it by always acquiring locks in the same order, holding fewer locks, or using tryLock with a timeout.
IntermediateQuick answer1 min read - What does the volatile keyword do in Java, and does it make count++ safe?
volatile guarantees that a write by one thread is immediately visible to other threads and prevents certain reordering. It does not make compound actions like count++ atomic, so a counter still needs synchronized or AtomicInteger.
IntermediateQuick answer1 min read - What is the difference between a synchronized method and a synchronized block in Java?
A synchronized method locks the whole method on this (or the Class for static methods). A synchronized block locks only the lines inside it, on any object you pick, so threads wait less and you can use separate locks for separate data.
IntermediateQuick answer1 min read - What is the difference between Runnable and Callable, and what is a Future?
Runnable.run returns nothing and cannot throw checked exceptions. Callable.call returns a value and may throw. Submitting a Callable to an ExecutorService gives a Future, a handle you use to fetch the result later.
IntermediateQuick answer1 min read - What is the difference between wait() and sleep() in Java?
sleep() pauses the current thread for a time and keeps any lock it holds. wait() must be called inside a synchronized block, releases that lock, and pauses until notify or notifyAll is called or the timeout ends.
IntermediateQuick answer1 min read - Why use ExecutorService instead of creating threads with new Thread?
Thread creation is costly and unbounded threads can exhaust memory. An ExecutorService reuses a fixed set of worker threads, queues extra tasks, returns Futures, and offers an orderly shutdown.
IntermediateQuick answer1 min read