Java interview questions

Master Java interview questions with 51+ curated problems, answer outlines, and placement-focused preparation.

Preview Questions

  1. What happens if you call start( ) twice on the same Thread object? And what if you call run( ) directly instead of start( )?

    If you call the start() method twice on the same Thread object, it will throw an IllegalThreadStateException because a thread can be started only once. Once a thread has completed its execution, it cannot be restarted...

  2. Suppose you override the equals( ) method in your class but forget to override hashCode( ). What real problem might occur when storing your objects in a HashSet?

    If you override the `equals()` method in your class but forget to override the `hashCode()` method, objects that are considered equal by `equals()` may still have different hash codes. Since `HashSet` and other...

  3. Suppose two threads are waiting on the same object lock using wait( ). When notify( ) is called, how many threads will wake up and why?

    When two threads are waiting on the same object lock using the `wait()` method, and the `notify()` method is called, only one of those waiting threads will be awakened. The thread that gets notified is chosen randomly...

  4. What is the difference between fail-fast and fail-safe iterators, and can you name some collections that use each type?

    The main difference between fail-fast and fail-safe iterators is how they behave when a collection is modified while being iterated. Fail-fast iterators immediately throw a `ConcurrentModificationException` if the...

  5. What happens if you modify a collection while iterating over it using a for-each loop?

    If you modify a collection while iterating over it using a for-each loop, you will usually get a `ConcurrentModificationException`. This happens because the for-each loop internally uses an `iterator`, and when the...

  6. How does volatile differ from synchronized? Can volatile alone ensure thread safety?

    The `volatile` keyword and the `synchronized` keyword are both used in multithreading, but they serve different purposes. The `volatile` keyword ensures that the value of a variable is always read from the main memory...

  7. What is the difference between == and .equals( ) in Java?

    The `==` operator and the `.equals()` method are both used for comparison in Java, but they work differently. The `==` operator compares whether two references point to the same memory location, meaning it checks if...

  8. What is the difference between String, StringBuilder, and StringBuffer?

    The main difference between `String`, `StringBuilder`, and `StringBuffer` lies in "mutability" and "thread safety". A `String` in Java is `immutable`, meaning once a string object is created, its value cannot be...