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. Can static, private and final methods be overridden in Java?

    No. Final methods are forbidden from overriding, private methods are invisible to subclasses, and static methods belong to the class, so a same-named subclass method only hides the parent one instead of overriding it.

    IntermediateQuick answer1 min read
  2. What does this Java code print when a parent reference holds a child object?

    Methods are looked up on the real object at runtime, so the child version runs. Fields are looked up on the reference type at compile time, so the parent field is read. Fields are never polymorphic.

    IntermediateQuick answer1 min read
  3. When should you use composition instead of inheritance in Java?

    Use inheritance for a true is-a relationship and composition for has-a. Composition is usually safer because the classes stay loosely coupled and you can change the part at runtime, while inheritance ties the child tightly to the parent.

    IntermediateQuick answer1 min read
  4. Why does Java not allow a class to extend more than one class?

    To avoid the diamond problem, where two parents define the same method and the child cannot tell which one to inherit. Java allows multiple interfaces instead, and since Java 8 a conflicting default method must be resolved explicitly.

    IntermediateQuick answer1 min read