386 Java Developer Interview Questions & Answers

139 top • 34 Amazon • 36 Apple • 41 Google • 35 Meta • 39 Microsoft • 31 Netflix • 31 NVIDIA

Java Developer icon

Questions with Detailed ExplanationsWith Detailed Explanations

(Last Updated: August 28, 2026)

11. Why are Strings immutable in Java?Language SpecificEasy

Question Details

Explain why String objects are immutable and how that affects security, caching, and reuse.

Short Interview Answer (30-60 seconds)

Strings are immutable in Java, so the character content of a String object cannot change after creation. Operations such as concat, replace, and toUpperCase return a String result instead of modifying the original object. This makes Strings safe to share, allows literals to be reused through the string pool, and keeps their equality and hash behavior stable when they are used as collection keys.

Detailed Explanation

A text value in Java cannot be changed after it is created. An operation may look as though it changes the value, but it returns another value and leaves the first one untouched. This makes shared text more predictable because one part of a program cannot unexpectedly alter text used by another part. It also lets Java safely reuse common text values. The main cost is that repeated changes may create many temporary values and use more memory until those unused values are removed.

Useful Questions to Ask the Interviewer
  1. Should I explain the difference between a string literal and a String created with new?
  2. Should I discuss repeated concatenation and StringBuilder?
Why are Strings immutable in Java? diagram
How to Explain It in an Interview

A String object is immutable. After Java creates it, its character content cannot be changed. The String class does not expose operations that modify that content, and the class is final, so a subclass cannot replace this behavior.

Methods such as concat, replace, substring, and toUpperCase return a String result. They do not change the original object. A method may return the same object when no content change is needed, so a new allocation is not guaranteed for every call.

Immutability makes Strings safe to share between methods and threads. It also makes the string pool practical because several references can safely use the same pooled literal. No caller can change the shared content.

A String also has stable equals and hashCode results because its content never changes. This makes it a reliable key for HashMap and a reliable element for HashSet.

Immutability reduces risks caused by unexpected changes to values such as class names, paths, addresses, and configuration keys. It does not validate those values or make sensitive text disappear from memory.

The tradeoff is allocation. Repeated concatenation, especially inside a loop, can create temporary String objects. Use StringBuilder when text must be changed many times, then call toString when the final immutable value is ready.

Why Interviewers Ask This

Interviewers ask this question to check whether a candidate understands object immutability, String method behavior, safe object sharing, the string pool, and the use of Strings as keys in hash based collections. They also want to see whether the candidate can explain the allocation cost of repeated text changes and choose StringBuilder when mutable text is more appropriate.

Common interview mistakes

A common mistake is saying that a String variable cannot change. The variable can be assigned a reference to another String, but the original String object remains unchanged. Another mistake is calling concat, replace, or toUpperCase without using the returned value and expecting the original value to change. Candidates may also say that every String method always creates a new object, which is not guaranteed when the result is unchanged. Another mistake is claiming that immutability alone validates input or completely protects sensitive text in memory. Repeated concatenation in a large loop is also a common performance mistake when StringBuilder would avoid many temporary results.

Interview tip

Start by separating the String object from the variable that references it. State that the object content cannot change, but the variable can reference another String. Then explain safe sharing, string pool reuse, stable hash behavior, and the allocation tradeoff. Finish by naming StringBuilder as the normal choice for repeated text changes.

Interviewer may ask next
What is the difference between a string literal and a String created with new?

A string literal normally refers to the canonical String object stored in the string pool, while new String with that literal creates a distinct String object. Both objects are immutable and may contain equal text, so equals can return true even when the references are different. Calling intern returns the canonical pooled reference. This matters because reference identity and content equality are different concepts.

Why is StringBuilder preferred for repeated concatenation?

StringBuilder is preferred because it uses mutable internal storage and can append text repeatedly without producing a separate String result for each append operation. This usually reduces temporary allocations and copying when building text in a loop. The tradeoff is that StringBuilder is mutable and is not designed for unsynchronized sharing between threads. The final value should be converted to an immutable String with toString.

12. What is a constructor?Language SpecificEasy

Question Details

Define a constructor in Java and explain when it runs and what problem it solves.

Short Interview Answer (30-60 seconds)

A constructor is a special declaration that initializes a new Java object. It has the same name as its class and does not declare a return type. Java invokes constructors as part of object creation. I use them to require important values, initialize fields, and make sure an object starts in a valid state.

Detailed Explanation

A constructor is the setup process used when a program creates a new object from a class. It gives the object the starting information it needs before normal use. For example, a customer object may need a name when it is created. The constructor can require that name and store it immediately. This helps stop incomplete or invalid objects from entering the program. A constructor may also choose safe starting values when some information is optional. Construction finishes only if every required setup step completes without an error.

Useful Questions to Ask the Interviewer
  1. Should the object require certain values when it is created?
  2. Should I explain constructor overloading, chaining, and compiler generated constructors?
What is a constructor? diagram
How to Explain It in an Interview

A constructor is a special declaration used to initialize an object. Its name must match the simple name of the class, and it does not declare a return type, not even void.

When an object is created, Java first allocates memory and gives all instance fields their default values. Numeric fields receive zero, boolean fields receive false, and reference fields receive null. Java then follows the constructor chain through the class hierarchy.

In Java 25, a constructor body may contain a prologue before an explicit this(...) or super(...) invocation. The prologue runs in an early construction context, so it generally cannot read the instance under construction, invoke its instance methods, or use this or super as an ordinary value. Java 25 does permit a limited assignment to a field declared in the current class before the explicit invocation. After the prologue, the constructor may explicitly invoke at most one alternate constructor with this(...) or direct superclass constructor with super(...). When no explicit invocation is written, Java normally supplies an implicit super() call. The selected superclass constructor completes before the remaining initialization of the current class continues.

For the current class, instance field initializers and instance initializer blocks run in their source order. The constructor body then runs. If every constructor in the chain completes normally, object creation completes. A constructor may throw an exception, in which case the creation expression does not produce the new object reference for the caller.

A class may declare several constructors with different parameter lists. This is constructor overloading. Constructors are not inherited and cannot be overridden. An abstract class can have constructors because its state must be initialized when a concrete subclass is created. An interface cannot declare a constructor.

When a class declares no constructor, the compiler may provide a constructor that takes no arguments. It invokes the superclass constructor with no arguments. If the superclass does not have an accessible matching constructor, compilation fails. Once the class declares any constructor, Java does not add this compiler generated constructor.

In production code, constructors should validate required inputs and establish valid object state. Avoid database calls, network calls, thread startup, publishing this, or calling overridable methods during construction. Such work can make creation slow, expose a partly initialized object, or run subclass behavior before subclass initialization is complete.

Why Interviewers Ask This

Interviewers ask this question to check whether the candidate understands how Java initializes a new object before normal use. They also evaluate knowledge of constructor syntax, constructor chaining, initialization order, compiler generated constructors, inheritance rules, and practical judgment about keeping object creation safe and predictable.

Common interview mistakes

Common mistakes include declaring a return type and accidentally creating a normal method, expecting Java to add a constructor with no arguments after another constructor has been declared, and assuming constructors are inherited or overridden. For Java 25, it is also a mistake to repeat the older rule that this(...) or super(...) must always be the first statement. A restricted prologue may appear before the explicit constructor invocation, but it runs in an early construction context and generally cannot read or invoke behavior on the instance under construction; Java 25 permits limited assignment to fields declared in the current class. Other mistakes include forgetting that the superclass constructor still runs before normal instance initialization continues, performing slow external work during construction, calling overridable methods from a constructor, or allowing this to escape before initialization is complete.

Interview tip

Start by defining a constructor and stating that Java invokes it during object creation. Then mention its naming rule, lack of a return type, constructor chaining, the compiler generated constructor rule, and its practical purpose of creating valid object state. For Java 25, qualify the older first-statement rule: a restricted early-construction prologue may appear before an explicit this(...) or super(...) invocation.

Interviewer may ask next
What happens if a class does not declare any constructor?

The compiler provides a constructor with no arguments when the class declares no constructor, subject to the rules for that class kind. That constructor invokes the direct superclass constructor with no arguments. This matters because compilation fails when no accessible matching superclass constructor exists. Once the class declares any constructor, Java does not add the compiler generated constructor.

Should a constructor perform database calls or other expensive work?

Usually, it should not perform expensive external work. A constructor should mainly validate inputs and establish valid object state. Database calls, network calls, and thread startup increase creation time and make failures harder to control. A factory method or separate operation can make that work clearer and easier to test. The tradeoff is that callers must then manage an additional creation or initialization step.

13. What is constructor overloading?Language SpecificEasy

Question Details

Explain constructor overloading and how multiple constructors can be used to initialize the same class in different ways.

Short Interview Answer (30-60 seconds)

Constructor overloading means defining multiple constructors in the same Java class with different parameter lists. It lets callers create the same type of object with different starting information. Java selects the applicable constructor at compile time from the supplied arguments. I usually keep one constructor as the main initializer and let simpler constructors call it with this so validation and default values remain consistent.

Detailed Explanation

See the Code while reading this explanation.

Constructor overloading gives people more than one way to create the same kind of object. For example, one person may know only a name, while another may know both a name and an age. The class can accept either amount of information and fill in sensible values for anything missing. This makes object creation easier for callers. The important design goal is to keep every creation path consistent, so all created objects follow the same rules and begin in a valid state.

Useful Questions to Ask the Interviewer
  1. Which values are required when the object is created?
  2. Which values may use defaults?
  3. Should invalid values be rejected immediately?
What is constructor overloading? diagram
How to Explain It in an Interview

Constructor overloading means declaring two or more constructors in one class with different parameter lists. The constructors may differ by parameter count, parameter types, or parameter order. Changing only parameter names is not enough because parameter names are not part of the constructor signature.

Java performs overload resolution at compile time. It examines the arguments in the new expression and selects the most specific applicable constructor. For example, new User("Asha") calls a constructor that accepts a String, while new User("Asha", 28) calls one that accepts a String and an int. If no constructor is applicable, or if multiple constructors are equally applicable and neither is more specific, compilation fails.

A useful pattern is constructor chaining. A shorter constructor calls another constructor in the same class by using this(...) with suitable default values. In Java 25, the this(...) invocation does not have to be the first statement: a restricted prologue may prepare or validate arguments before it. That prologue runs in an early construction context and generally cannot read the instance under construction or invoke its instance methods, although Java 25 permits limited assignment to fields declared in the current class. Keeping shared validation and field assignment in one constructor still reduces duplicated logic.

Constructors are not inherited and cannot be overridden. A subclass constructor may call a superclass constructor by using super(...). In Java 25, permitted prologue statements may appear before super(...), subject to the same early-construction restrictions. A constructor body can contain at most one explicit constructor invocation, so it cannot directly invoke both this(...) and super(...). A chain that begins with this(...) eventually reaches a constructor that invokes a superclass constructor. If Java supplies an implicit super() call but the superclass has no accessible constructor with no arguments, compilation fails.

Constructor overloading works well when a class has a small number of clear creation options. Too many similar constructors can become difficult to read, especially when several parameters have the same type. Named factory methods or a builder can then make the caller's intent clearer.

Constructor chaining does not allocate another instance. One new expression creates one object. Chaining adds normal constructor invocation and initialization work, but it does not change the overall memory requirement or introduce a separate object allocation.

Code
public class Main {

    static final class User {

        private final String name;
        private final int age;

        User(String name) {
            this(name, 0);
        }

        User(String name, int age) {
            if (name == null || name.isBlank()) {
                throw new IllegalArgumentException("Name is required");
            }
            if (age < 0) {
                throw new IllegalArgumentException("Age cannot be negative");
            }
            this.name = name;
            this.age = age;
        }

        @Override
        public String toString() {
            return "User{name='" + name + "', age=" + age + "}";
        }
    }

    public static void main(String[] args) {
        User first = new User("Asha");
        User second = new User("Ravi", 28);

        System.out.println(first);
        System.out.println(second);
    }
}
Why Interviewers Ask This

Interviewers ask this question to check whether the candidate understands how Java chooses among overloaded constructors, how a class can support different initialization needs, and how constructor chaining prevents duplicated setup logic. It also tests knowledge of parameter lists, default constructors, ambiguous calls, validation, and object initialization.

Common interview mistakes

Common mistakes include declaring constructors with identical parameter types and expecting different parameter names to distinguish them, repeating validation in every constructor, and applying the pre-Java-25 rule that this(...) or super(...) must always be the first statement. Java 25 allows a restricted prologue before the explicit constructor invocation, but that early construction context generally cannot read or invoke behavior on the instance under construction; limited assignment to fields declared in the current class is permitted. Another mistake is assuming constructor chaining creates another object. Developers may also expect a constructor with no arguments to exist after declaring another constructor, but Java supplies a default constructor only when the class declares no constructor. Passing null can also make a call ambiguous when unrelated reference types are overloaded.

Interview tip

Start by saying that constructor overloading provides several ways to initialize the same class through different parameter lists. Then show a small example and explain constructor chaining with this(...). Mention that Java resolves the constructor at compile time, one new expression creates one object, and Java 25 permits a restricted early-construction prologue before this(...) or super(...). Too many similar constructors may be clearer as named factory methods or a builder.

Interviewer may ask next
What happens if passing null matches more than one overloaded constructor?

The call fails to compile when multiple constructors are equally applicable to null and neither parameter type is more specific. For example, constructors accepting String and Integer make new Example(null) ambiguous because both reference types can receive null. This matters because overload resolution happens at compile time. An explicit cast can select one constructor, but clearer factory method names may reduce confusion.

When should you use a builder instead of many overloaded constructors?

Use a builder when an object has many optional values or when several constructor parameters have the same type. A builder gives each value a name at the call site, which improves readability and reduces argument ordering mistakes. The tradeoff is additional code and usually one temporary builder object. A few simple constructor overloads remain preferable when the valid creation options are small and obvious.

14. What is inheritance in Java?Language SpecificEasy

Question Details

Explain inheritance in Java and why it is useful for code reuse and extensibility.

Short Interview Answer (30-60 seconds)

Inheritance in Java lets one class extend another class and reuse accessible behavior. The subclass can add new behavior or override inherited instance methods. Java allows a class to extend only one direct superclass, although it can implement multiple interfaces. I use inheritance when there is a genuine is a relationship and the subclass can safely follow the superclass contract.

Detailed Explanation

See the Code while reading this explanation.

Inheritance lets one kind of object build on another kind of object. For example, a dog can share common behavior with an animal while also providing its own behavior. This can reduce repeated code and lets related objects be handled through one common type. The key design question is whether the new type is truly a more specific form of the existing type. Sharing a few actions is not enough by itself. A poor relationship can create tight connections and make later changes difficult.

Useful Questions to Ask the Interviewer
  1. Should the example use a concrete class, an abstract class, or an interface?
  2. Should I also explain method overriding and runtime method selection?
  3. Would you like a comparison between inheritance and composition?
What is inheritance in Java? diagram
How to Explain It in an Interview

In Java, a class inherits from another class by using the extends keyword. The existing class is the superclass, and the new class is the subclass. A subclass inherits accessible members according to Java access rules. Private members are not directly accessible from the subclass.

Constructors are not inherited. A subclass constructor must invoke a superclass constructor. It can do this explicitly with super. When the source code does not contain an explicit constructor invocation, the compiler inserts a call to the no argument superclass constructor. Compilation fails if that constructor is not accessible or does not exist.

A subclass can override an inherited instance method by declaring a compatible method with the same signature and return type rules. When that method is called through a superclass reference, Java selects the implementation from the actual object at runtime. This is dynamic dispatch. Static methods are hidden rather than overridden. Final methods cannot be overridden. Private methods are not overridden because they are not inherited by the subclass.

Java allows a class to extend only one direct superclass. A class can still implement multiple interfaces. Every class except Object has one direct superclass, and all class inheritance chains eventually reach Object.

Inheritance is useful when the subclass is a valid specialized form of the superclass and preserves its expected behavior. For example, Dog can extend Animal because every Dog can be treated as an Animal. Avoid inheritance when the goal is only code reuse or when the relationship may change. Composition is often more flexible because one object can contain another object and delegate work to it.

Creating a subclass object does not create a separate superclass object. It creates one object whose class includes the instance state declared across its class hierarchy. The exact memory layout is a JVM implementation detail. Method calls through inheritance normally have constant time behavior, but deep hierarchies can increase design complexity and make code harder to maintain.

Code
public class Main {

    static class Animal {

        private final String name;

        Animal(String name) {
            this.name = name;
        }

        protected String name() {
            return name;
        }

        void speak() {
            System.out.println(name() + " makes a sound");
        }
    }

    static class Dog extends Animal {

        Dog(String name) {
            super(name);
        }

        @Override
        void speak() {
            System.out.println(name() + " barks");
        }
    }

    public static void main(String[] args) {
        Animal animal = new Dog("Buddy");
        animal.speak();
    }
}
Why Interviewers Ask This

Interviewers ask this question to check whether the candidate understands class relationships, inherited members, constructor rules, method overriding, dynamic dispatch, access control, and when composition is a better design choice.

Common interview mistakes

Common mistakes include saying that Java supports multiple class inheritance, assuming constructors are inherited, trying to override final or private methods, and treating static method hiding as method overriding. Another mistake is using inheritance only to reuse code without checking whether the subclass is truly a valid form of the superclass. Candidates also sometimes assume that the reference type decides which overridden method runs, but Java uses the actual object type for overridden instance methods.

Interview tip

Start with the extends relationship. Then explain constructor chaining, method overriding, and dynamic dispatch with one small example. Mention that Java allows one direct superclass and multiple implemented interfaces. Finish by explaining that inheritance should model a real is a relationship and that composition is often safer for simple code reuse.

Interviewer may ask next
What happens when a subclass overrides a method but the object is stored in a superclass reference?

The subclass implementation runs for an overridden instance method. Java uses dynamic dispatch, so it selects the method from the actual object type at runtime. This matters because code can use a general superclass reference while each subclass provides specialized behavior. Static methods, fields, and private methods do not use this overriding behavior.

When should composition be preferred over inheritance?

Composition should be preferred when one class needs another object's behavior but is not a true specialized form of that class. The containing object delegates work to another object instead of extending it. This reduces coupling and makes behavior easier to replace, test, and change. Inheritance is appropriate for a stable is a relationship, while composition usually provides more flexibility in production code.

15. What is encapsulation?Language SpecificEasy

Question Details

Explain encapsulation and how access control helps protect object state.

Short Interview Answer (30-60 seconds)

Encapsulation means keeping an object’s state inside its class and controlling access through a clear public interface. In Java, I usually make fields private and expose methods that validate every change. This protects class rules, prevents uncontrolled updates, and lets the internal implementation change without forcing callers to change.

Detailed Explanation

See the Code while reading this explanation.

Encapsulation means that one part of a program takes responsibility for its own information. Other parts cannot change that information in any way they choose. They must use the safe actions that are provided. For example, an inventory item should not allow its quantity to become negative. It can provide actions to add or remove stock and check each request before accepting it. This keeps the information valid, reduces mistakes, and allows the inside design to change later without affecting every place that uses it.

Useful Questions to Ask the Interviewer
  1. Can the state change after the object is created?
  2. Which changes should callers be allowed to request?
  3. What rules must every change preserve?
What is encapsulation? diagram
How to Explain It in an Interview

In Java, encapsulation means keeping state and the code that manages that state inside one class. The class exposes a controlled public interface while hiding details that callers do not need.

A common approach is to declare fields private. Other classes cannot access those fields directly. They must call methods provided by the class. Those methods can validate input and preserve the class rules before changing the state.

For example, an InventoryItem class can keep its quantity private. The addStock method accepts only a positive amount. The removeStock method rejects a nonpositive amount and also rejects a request larger than the available quantity. This ensures that the quantity never becomes negative through the class interface.

Java access control supports this design. private limits access to the declaring class. Package access allows access from the same package. protected allows same package access and access through inheritance under Java rules. public allows access from any code that can access the class.

Encapsulation does not mean adding a getter and setter for every field. An unrestricted setter may allow invalid state. A better design exposes meaningful operations that represent valid changes.

Encapsulation also has limits. It does not make a mutable class thread safe. Multiple threads may still require synchronization or another concurrency design. It also does not protect a mutable object that is returned directly. A class may need to return an immutable view or a defensive copy.

A normal method call has no meaningful asymptotic cost beyond the work performed by that method. Access control itself does not add per object memory. Defensive copies can require extra time and memory because they create new objects. In production, the main value is correctness, maintainability, and reduced coupling.

Code
public class Main {

    public static void main(String[] args) {
        InventoryItem item = new InventoryItem(10);
        item.addStock(5);
        item.removeStock(3);

        System.out.println(item.getQuantity());
    }

    static final class InventoryItem {

        private int quantity;

        InventoryItem(int startingQuantity) {
            if (startingQuantity < 0) {
                throw new IllegalArgumentException("Starting quantity cannot be negative");
            }
            this.quantity = startingQuantity;
        }

        public int getQuantity() {
            return quantity;
        }

        public void addStock(int amount) {
            if (amount <= 0) {
                throw new IllegalArgumentException("Amount must be positive");
            }
            quantity = Math.addExact(quantity, amount);
        }

        public void removeStock(int amount) {
            if (amount <= 0) {
                throw new IllegalArgumentException("Amount must be positive");
            }
            if (amount > quantity) {
                throw new IllegalArgumentException("Not enough stock");
            }
            quantity -= amount;
        }
    }
}
Why Interviewers Ask This

Interviewers ask this question to check whether a candidate understands how a Java class protects its internal state. They also evaluate whether the candidate can choose suitable access levels, preserve class rules, avoid exposing mutable data, and design a small public interface that remains safe as the implementation changes.

Common interview mistakes

A common mistake is saying that encapsulation only means making fields private. Private fields help, but the public methods must also preserve the class rules. Another mistake is creating a public setter for every field without validation. Returning a mutable internal collection directly can also expose the state because callers may change it without using the class methods. Developers may also assume that encapsulation makes a class thread safe, but access modifiers alone do not coordinate concurrent changes.

Interview tip

Begin by saying that encapsulation protects object state through controlled access. Then give one simple example with a private field and a method that validates changes. Explain that good encapsulation exposes meaningful behavior instead of unrestricted setters.

Interviewer may ask next
Does making every field private make a Java class fully encapsulated?

No. Private fields are only one part of encapsulation. The public interface must also prevent callers from breaking the class rules. A setter that accepts invalid values or a getter that returns a mutable internal object can still expose the state. This matters because the class may look protected while callers can still change its data indirectly.

What is the tradeoff between returning a defensive copy and returning the internal mutable object?

Returning a defensive copy protects encapsulation because callers receive a separate object and cannot modify the original state through that reference. The tradeoff is extra allocation, copying time, and memory use. Returning the internal object avoids that cost but exposes the state. In production, an immutable view or a carefully designed read operation may provide a better balance when copying is expensive.

16. What is polymorphism?Language SpecificEasy

Question Details

Explain compile-time and runtime polymorphism in Java with practical examples.

Short Interview Answer (30-60 seconds)

Polymorphism means that the same Java type or method name can support different behavior. Compile time polymorphism is commonly shown with method overloading, where the compiler selects an applicable method from the method name and parameter types. Runtime polymorphism uses method overriding, where an interface or parent reference can point to different objects and Java runs the overridden instance method of the actual object. In practice, runtime polymorphism helps code depend on stable interfaces instead of concrete classes.

Detailed Explanation

See the Code while reading this explanation.

Polymorphism means that the same request can produce different behavior depending on the object that receives it. For example, an application can ask different payment objects to process a payment. A card object and a bank object can respond in their own ways, while the calling code uses the same request. Java supports one form where the compiler selects a method before the program runs and another form where Java selects an overridden method while the program is running. This makes code easier to extend when several objects follow the same contract.

Useful Questions to Ask the Interviewer
  1. Should I explain both method overloading and method overriding?
  2. Would you like a practical example using an interface and two implementations?
What is polymorphism? diagram
How to Explain It in an Interview

Compile time polymorphism is commonly demonstrated with method overloading. A class can declare several methods with the same name but different parameter lists. During compilation, Java checks the compile time argument types, finds the applicable overloads, and selects the most specific valid method. A different return type alone does not create a valid overload.

Runtime polymorphism is demonstrated with method overriding. An interface or parent reference can point to an object of an implementing or child class. When code calls an overridable instance method, Java uses dynamic method dispatch. The selected implementation depends on the actual object at runtime, not only on the declared reference type.

In the example, a PaymentProcessor reference points first to a CardPayment object and then to a BankPayment object. Calling process runs the implementation provided by each actual object. The caller can work with the PaymentProcessor contract without containing separate logic for every payment class.

Runtime polymorphism is useful when several classes share one contract but need different behavior. Common production examples include payment providers, notification channels, storage adapters, service implementations, and test substitutes.

Inheritance should not be used only for code reuse. Composition is often clearer when there is no true parent and child relationship. Fields are resolved from the declared reference type. Static methods are hidden rather than overridden. Private methods are not inherited as overridable methods, and final methods cannot be overridden.

Assigning an object to an interface or parent reference does not copy the object or create another object. The reference value is copied. Dynamic calls may have some dispatch work, but the JVM can optimize frequently executed calls, including through inlining when runtime conditions allow it. No specific optimization is guaranteed.

Code
public class Main {

    interface PaymentProcessor {
        void process(double amount);
    }

    static class CardPayment implements PaymentProcessor {

        @Override
        public void process(double amount) {
            System.out.println("Card payment: " + amount);
        }
    }

    static class BankPayment implements PaymentProcessor {

        @Override
        public void process(double amount) {
            System.out.println("Bank payment: " + amount);
        }
    }

    static void printResult(String message) {
        System.out.println(message);
    }

    static void printResult(double amount) {
        System.out.println("Processed amount: " + amount);
    }

    public static void main(String[] args) {
        PaymentProcessor first = new CardPayment();
        PaymentProcessor second = new BankPayment();

        first.process(100.0);
        second.process(200.0);

        printResult("Payments completed");
        printResult(300.0);
    }
}
Why Interviewers Ask This

Interviewers ask this question to check whether a candidate understands method overloading, method overriding, inheritance, interfaces, reference types, and dynamic method dispatch. They also want to see whether the candidate can choose a shared contract for several implementations without confusing compile time method selection with runtime method selection.

Common interview mistakes

A common mistake is saying that Java chooses an overload from the actual runtime object. Overload selection uses compile time types and method applicability. Another mistake is assuming that fields use runtime polymorphism. Field access uses the declared reference type. Static methods are hidden, not overridden. Private and final methods cannot participate in normal overriding. Developers may also cast a reference to an unrelated concrete type, which can cause ClassCastException. Another mistake is creating an inheritance hierarchy only to reuse code when composition would express the relationship more clearly.

Interview tip

Start with one clear sentence: polymorphism lets the same type or method name support different behavior. Then separate overloading from overriding. Say that overload selection happens during compilation, while overridden instance method selection depends on the actual object at runtime. Finish with one small interface example and mention that reference assignment does not copy the object.

Interviewer may ask next
What happens if an overloaded method is called through a parent reference that points to a child object?

The compiler first selects the overload using the compile time reference type, the compile time argument types, and the applicable method rules. The actual child object does not make Java select a different overload. After the method signature is selected, runtime dispatch can still choose a child override of that selected instance method. This matters because overloading and overriding are separate decisions made at different stages.

Does runtime polymorphism create an object copy or a guaranteed performance penalty?

No object copy is created simply because an object is assigned to an interface or parent reference. Java copies the reference value, while both references can point to the same object. An overridden call may require dynamic dispatch, but the JVM can optimize frequently executed calls and may inline them when conditions allow. The main tradeoff is often design complexity and indirection rather than a guaranteed measurable slowdown.

17. What is abstraction?Language SpecificEasy

Question Details

Explain abstraction and how Java lets you expose what is needed while hiding implementation details.

Short Interview Answer (30-60 seconds)

Abstraction means exposing what an object can do while hiding the details of how it does the work. In Java, I usually express it with an interface or an abstract class, then put the actual behavior in concrete classes. Callers depend on the abstraction, so an implementation can change without forcing every caller to change.

Detailed Explanation

See the Code while reading this explanation.

Abstraction means giving people a simple way to use something without making them understand every inner step. A driver presses a brake pedal without needing to know how each part of the braking system works. In software, one part can ask another part to perform an action through a clear set of choices. The hidden work can then change while the visible way of using it stays the same. This keeps large programs easier to understand, test, and change when the boundary is chosen carefully.

Useful Questions to Ask the Interviewer
  1. Should the example use an interface, an abstract class, or both?
  2. Do the implementations need shared data or shared behavior?
  3. Should callers be able to replace one implementation with another?
What is abstraction? diagram
How to Explain It in an Interview

In Java, abstraction is commonly expressed with interfaces and abstract classes. An interface defines a contract that implementing classes agree to follow. An abstract class can define abstract methods and can also contain fields, constructors, and shared implemented methods.

For example, a PaymentProcessor interface can declare a process method. CardPaymentProcessor and BankPaymentProcessor can implement that method differently. A checkout method can accept PaymentProcessor, so it does not need to know the internal steps used by either implementation.

When checkout calls process, Java uses dynamic dispatch for the overridden instance method. The method from the actual object runs. A PaymentProcessor reference that points to a CardPaymentProcessor object therefore runs the card implementation. This rule does not apply in the same way to static, private, or final methods because they are not overridden through normal dynamic dispatch.

Use abstraction when several implementations should follow one stable contract, when details may change, or when callers should not depend on a concrete class. Prefer an interface when the main need is a contract. Consider an abstract class when closely related classes need shared state or shared implementation.

Abstraction is a design boundary, not automatic security. Public arguments, results, logs, exceptions, reflection, or direct use of a concrete class can still reveal details. Too many interfaces and layers can also make code harder to follow.

The exact call cost depends on the JVM and runtime profile. The JVM can optimize many interface and virtual calls, so this cost is usually not the main design concern. Declaring an interface or abstract class does not allocate an object. Memory is used when concrete objects and their fields are created.

Code
public class Main {

    interface PaymentProcessor {
        void process(int amountInCents);
    }

    static final class CardPaymentProcessor implements PaymentProcessor {

        @Override
        public void process(int amountInCents) {
            System.out.println("Card payment processed: " + amountInCents);
        }
    }

    static final class BankPaymentProcessor implements PaymentProcessor {

        @Override
        public void process(int amountInCents) {
            System.out.println("Bank payment processed: " + amountInCents);
        }
    }

    static void checkout(PaymentProcessor processor, int amountInCents) {
        processor.process(amountInCents);
    }

    public static void main(String[] args) {
        PaymentProcessor processor = new CardPaymentProcessor();
        checkout(processor, 2500);
    }
}
Why Interviewers Ask This

Interviewers ask this question to check whether a candidate understands how Java separates a public contract from implementation details. They also want to see whether the candidate can choose between an interface and an abstract class, explain runtime method selection, and avoid adding unnecessary layers.

Common interview mistakes

A common mistake is saying abstraction only means using an abstract class. Interfaces also express abstraction. Another mistake is confusing abstraction with encapsulation. Abstraction presents the behavior that callers need, while encapsulation controls access to state and implementation. Candidates may also assume an interface creates an object or holds normal instance state. An interface defines a type and contract, while a concrete class creates the object. Another mistake is adding an interface for every class even when there is no useful boundary or likely need for another implementation.

Interview tip

Start with the practical meaning: expose required behavior and hide implementation details. Then name interfaces and abstract classes, explain when each is useful, and finish with a small example that shows dynamic dispatch through an abstraction.

Interviewer may ask next
What happens when an abstract class has an abstract method and a concrete subclass does not implement it?

The concrete subclass must implement the inherited abstract method or it will not compile. Only another abstract subclass may leave that method without an implementation. This matters because Java prevents creation of a concrete object whose required abstract behavior is missing.

When should you choose an interface instead of an abstract class?

Choose an interface when the main goal is a contract that unrelated classes can implement. Choose an abstract class when closely related classes need shared instance state, constructors, protected helpers, or common implementation. A class can implement several interfaces but can extend only one class. The tradeoff is greater flexibility with interfaces versus stronger support for shared code and state with abstract classes.

18. What is an interface?Language SpecificEasy

Question Details

Explain what an interface is, why it is used, and how it differs from a concrete class.

Short Interview Answer (30-60 seconds)

An interface defines a contract that implementing classes agree to follow. It describes required behavior without deciding how every class performs that behavior. Modern Java interfaces can also contain default, static, and private methods. I use an interface when different classes should support the same capability while keeping separate implementations. Unlike a concrete class, an interface cannot be instantiated directly and does not hold per object instance state.

Detailed Explanation

See the Code while reading this explanation.

An interface is an agreement that describes what an object can do. It lists actions that supporting objects must provide. Different objects can follow the same agreement while doing the work in their own way. This lets the rest of a program work with one shared promise instead of depending on one exact object. A concrete class is different because it provides the complete design used to create a working object. Before answering, I would clarify these points:

Useful Questions to Ask the Interviewer
  1. Should I cover only the basic rules or also modern interface methods?
  2. Should I compare interfaces with abstract classes as well as concrete classes?
What is an interface? diagram
How to Explain It in an Interview

In Java, an interface is a reference type that defines a contract. A class uses the implements keyword to accept that contract. The class must implement every inherited abstract method unless the class itself is abstract.

An interface cannot be instantiated directly. However, an interface variable can refer to an object whose class implements that interface. When code calls an interface method, Java selects the implementation belonging to the actual object at runtime. This behavior is dynamic dispatch.

An abstract interface method is implicitly public and abstract. An implementing method must therefore be public. Interface fields are implicitly public, static, and final. They are constants shared through the interface, not separate fields stored in each object.

Modern Java interfaces may contain default methods with a body, static methods owned by the interface, and private methods used by other interface methods. An interface has no constructor and cannot store mutable instance state. An interface may extend more than one interface, and a class may implement more than one interface.

Use an interface when callers should depend on a capability such as PaymentProcessor rather than one concrete implementation. This makes implementations easier to replace and test. Do not create an interface only to add another layer when no useful contract or alternative implementation is expected.

Calling a method through an interface reference does not copy or allocate another object. Only the reference value may be copied. Interface dispatch has no useful asymptotic complexity to report. Its exact runtime cost depends on the JVM, and the just in time compiler can often optimize and inline calls when the target implementation is known.

Code
interface PaymentProcessor {
    void process(int amount);
}

class CardPaymentProcessor implements PaymentProcessor {

    @Override
    public void process(int amount) {
        System.out.println("Card payment processed: " + amount);
    }
}

class CashPaymentProcessor implements PaymentProcessor {

    @Override
    public void process(int amount) {
        System.out.println("Cash payment processed: " + amount);
    }
}

public class Main {

    public static void main(String[] args) {
        PaymentProcessor first = new CardPaymentProcessor();
        PaymentProcessor second = new CashPaymentProcessor();

        first.process(100);
        second.process(50);
    }
}
Why Interviewers Ask This

Interviewers ask this question to check whether the candidate understands contracts, abstraction, implementation rules, multiple interface inheritance, runtime method selection, and the difference between an interface and a concrete class. It also tests whether the candidate can choose an interface for a useful design reason instead of adding an unnecessary layer.

Common interview mistakes

A common mistake is saying that an interface can never contain implementation. Modern Java interfaces can contain default, static, and private methods. Another mistake is trying to instantiate an interface directly. Developers may also forget that an implementing method must be public because an inherited abstract interface method is public. Another error is treating interface fields as normal object fields even though they are public, static, and final constants. Candidates also sometimes confuse implementing several interfaces with extending several classes.

Interview tip

Start by calling an interface a contract. Then explain that concrete classes implement it, objects are created from those concrete classes, and calls through an interface reference use the actual object implementation at runtime. Finish with one practical example and mention that a class can implement several interfaces.

Interviewer may ask next
What happens if two implemented interfaces provide the same default method?

The implementing class must resolve the conflict when two unrelated interfaces provide default methods with the same signature. The class overrides the method and supplies its own behavior, or it can explicitly call a selected interface default method from that override. This matters because Java cannot safely choose one inherited implementation without an explicit rule from the class.

When would you choose an abstract class instead of an interface?

Choose an abstract class when closely related subclasses need shared instance state, constructors, protected members, or substantial common implementation. Choose an interface when different classes need to share a capability contract without joining one class hierarchy. The main tradeoff is that a class can extend only one class, while it can implement several interfaces.

19. What is an abstract class?Language SpecificEasy

Question Details

Explain what an abstract class is and when you would choose it over an interface.

Short Interview Answer (30-60 seconds)

I would use an abstract class when closely related classes need a common base with shared state or shared implementation. An abstract class cannot be instantiated directly. It can contain abstract methods, concrete methods, fields, and constructors. A concrete subclass must implement any inherited abstract methods. I would choose an interface when I mainly need a contract that unrelated classes can implement, especially because a class can implement multiple interfaces but extend only one class.

Detailed Explanation

An abstract class is a common starting point for a group of closely related objects. You cannot create an object directly from it. Another class must build on it and complete any missing actions. The common class can store shared information and provide work that every child class can reuse. This reduces repeated logic and keeps common rules in one place. It is useful when the child classes belong to the same family and share both data and behavior. An interface is usually better when different kinds of objects only need to promise that they can perform certain actions.

Useful Questions to Ask the Interviewer
  1. Do the related classes need to share stored data or implemented behavior?
  2. Must a class support more than one independent contract?
  3. Is there a clear parent and child relationship between the types?
What is an abstract class? diagram
How to Explain It in an Interview

In Java, an abstract class is declared with the abstract keyword. Java does not allow code to create an instance of that class directly. A subclass must extend it. If the subclass is concrete, it must implement every inherited abstract method that has not already been implemented. A subclass may remain abstract and leave some methods incomplete.

An abstract class can contain abstract methods and concrete methods. An abstract method declares a method name, parameters, return type, and possible exceptions, but it has no body. A concrete method contains reusable implementation. The class can also contain instance fields, static fields, constructors, static methods, and methods with normal Java visibility rules.

A constructor in an abstract class is valid even though the class cannot be instantiated directly. When Java creates a concrete subclass object, superclass construction runs before the subclass constructor body. This allows the abstract class to initialize shared state and validate common constructor arguments.

Choose an abstract class when the types are closely related and need shared instance state, constructor logic, protected helper methods, or a partly completed workflow. For example, several payment processors may extend one abstract processor that stores configuration and performs shared validation.

Choose an interface when the main goal is to define a capability or contract. A class can implement multiple interfaces, but it can extend only one class. This makes interfaces more flexible for unrelated types.

An abstract class does not provide a general performance advantage over an interface. Method calls may use dynamic dispatch in either design, and actual optimization depends on the JVM implementation. The memory used by an object depends on its instance fields and runtime representation, not simply on whether its parent is abstract. Deep inheritance can make code harder to change and test, so composition is often better when there is no true parent and child relationship.

Why Interviewers Ask This

Interviewers ask this question to check whether the candidate understands inheritance, object construction, method implementation, and type design in Java. They also want to see whether the candidate can choose correctly between an abstract class and an interface based on shared state, common behavior, class relationships, and the single class inheritance rule.

Common interview mistakes

A common mistake is saying that an abstract class can contain only abstract methods. It can also contain concrete methods, fields, constructors, static members, and normal initialization logic. Another mistake is trying to instantiate it directly. Some candidates also say that every subclass must implement every abstract method. An abstract subclass may leave methods incomplete, but the first concrete subclass must implement all remaining abstract methods. Another mistake is using inheritance only to reuse code when there is no true parent and child relationship. Composition may be clearer. Candidates should also remember that a class can extend only one class but can implement multiple interfaces.

Interview tip

Start with the design choice. Say that an abstract class is best for closely related classes that need shared state or implementation, while an interface is best for a contract or capability. Then mention that an abstract class cannot be instantiated, can have constructors and concrete methods, and uses the single class inheritance position.

Interviewer may ask next
Can an abstract class have a constructor, and when does that constructor run?

Yes, an abstract class can have a constructor. It runs as part of creating a concrete subclass object. The subclass constructor invokes a superclass constructor either explicitly with super arguments or implicitly with super when an accessible constructor without arguments exists. This matters because the abstract class can initialize shared fields and enforce common construction rules even though it cannot be instantiated directly. A constructor should avoid calling overridable instance methods because subclass fields may not be initialized yet.

When should you choose an interface instead of an abstract class?

Choose an interface when the main requirement is a contract that may be implemented by unrelated classes, or when a class must support several independent capabilities. Java allows a class to implement multiple interfaces but extend only one class. This matters because choosing an abstract class uses the single superclass position. The tradeoff is that an interface cannot provide per object instance fields or constructor logic, while an abstract class can store shared instance state and control common initialization.

20. What is a package in Java?Language SpecificEasy

Question Details

Explain how packages organize Java code and help avoid name conflicts.

Short Interview Answer (30-60 seconds)

A package in Java is a named namespace that groups related types such as classes, interfaces, records, and enums. It organizes a codebase and prevents name conflicts because two types can have the same simple name when they are in different packages. A source file normally declares its package at the top. Other source code can then refer to a type by its fully qualified name or use an import to write its simple name.

Detailed Explanation

A package is like a named section in a large filing cabinet. It keeps related items together and gives each item a more complete name. This is useful when two items have the same short name because their section names still make them different. In a large application, these named sections make code easier to find, understand, and maintain. They can also control whether some parts are available only to nearby code or to the wider application. The main idea is organization, clear naming, and controlled access.

Useful Questions to Ask the Interviewer
  1. Should I explain the usual directory layout and naming convention?
  2. Should I compare packages with Java modules?
  3. Should I explain package access rules?
What is a package in Java? diagram
How to Explain It in an Interview

A Java package is a named namespace that groups related top level types. A source file can declare its package with a statement such as package com.example.orders;. Package annotations, when present, appear immediately before the package keyword. The package declaration appears before import declarations and type declarations.

The package name becomes part of each top level type's fully qualified name. For example, com.example.orders.Order and com.example.shipping.Order are different types even though both have the simple name Order. Source code can use a fully qualified name directly or use an import so it can write the simple name.

Packages organize code by responsibility. A production application might use com.example.orders, com.example.payments, and com.example.customers. Reverse domain naming is a common convention because it lowers the chance that unrelated organizations choose the same package name.

Packages also affect access control. A top level type or member with no explicit access modifier has package access and is available only to code in the same package. A protected member is also accessible to code in the same package, with additional access available to subclasses under Java's protected access rules.

A package is not the same as a directory. Normal Java build tools expect source and class directories to match package names, but the package is defined by Java declarations and type names. A package also does not download libraries or select versions. Maven and Gradle manage dependencies. The Java Platform Module System groups packages into modules and can control which packages a module exports or opens.

Declaring or importing a package does not allocate memory for each application object and does not add a meaningful per operation time cost. Package names mainly affect naming, compilation, access checks, class lookup, and code organization.

Why Interviewers Ask This

Interviewers ask this question to check whether a candidate understands how Java organizes types, prevents naming conflicts, applies package access, and identifies classes during compilation and execution. It also tests whether the candidate can distinguish a package from a directory, an import, a dependency, and a Java module.

Common interview mistakes

A common mistake is saying that a package is only a directory. A matching directory structure is the normal convention used by compilers and build tools, but the package is a Java namespace declared in source code. Another mistake is thinking that an import copies code, loads a class immediately, or downloads a library. An import only allows a simple type name to be used in source code. Candidates may also confuse packages with modules, assume that subpackages inherit access from parent packages, or forget that com.example and com.example.orders are separate packages. The unnamed package should also be avoided in production because types in named packages cannot import or otherwise refer to types in the unnamed package by ordinary Java source rules.

Interview tip

Start by saying that a package is a namespace for related Java types. Use two Order classes in different packages to explain conflict prevention. Then mention package access and clearly separate packages from directories, imports, dependencies, and modules.

Interviewer may ask next
Does a subpackage automatically have access to package access members in its parent package?

No. Java treats a parent package and a subpackage as separate packages. Code in com.example.orders.internal does not receive package access to members in com.example.orders. This matters because the dotted names look hierarchical to people, but Java access control does not create an inheritance relationship between packages. The code must use an accessible API, satisfy the exact protected access rules when inheritance applies, or place closely related implementation types in the same package.

What is the difference between a package, an import, and a Java module?

A package provides a namespace for types and participates in access control. An import only lets source code use a simple type name instead of a fully qualified name. A Java module is a larger configuration and encapsulation unit that contains packages, declares required modules, and controls which packages it exports or opens. Packages are simple and used throughout Java, while modules provide stronger boundaries but require additional configuration and careful dependency design.

More questions load as you scroll

Disclaimer: This interview guide is for educational and informational purposes only. It is designed to help readers prepare, but it does not guarantee any interview result, hiring decision, offer, or outcome. Interview questions, hiring criteria, and preferred answers can vary by employer, interviewer, industry, location, and time. The examples and explanations reflect the authors' research and judgment, are provided without warranties of any kind, and should not be treated as the only correct approach. Diagrams are simplified illustrations intended to highlight the main components and their interactions; actual systems and implementations may be more complex. Alternative approaches may be equally valid or better suited to a particular question, context, or interviewer. To the fullest extent permitted by applicable law, the author, contributors, and publisher are not liable for decisions made, actions taken, or losses incurred based on this guide.