Interview Q&A / Java

INTERVIEW Q&A · 72 QUESTIONS

Java interview questions

Collections, the JVM, strings, exceptions and threads, the backbone of most campus placement rounds.

  1. Should you extend Thread or implement Runnable in Java?

    Implement Runnable in most cases. It separates the task from the thread, leaves your class free to extend something else, and works with thread pools. Extending Thread only makes sense if you are changing the thread behaviour itself.

    BeginnerQuick answer1 min read
  2. What happens if you call run() instead of start() on a Java thread?

    start() creates a new thread of execution and calls run() on it. Calling run() directly is an ordinary method call on the current thread, so no concurrency happens. Calling start() twice throws IllegalThreadStateException.

    BeginnerQuick answer1 min read
  3. 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
  4. 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
  5. 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
  6. 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
  7. 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
  8. 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