LearnFrenzy
Sign in Take a free test

Java Programming interview · Set 1 of 13

Core Java

  • 6 follow-up questions
  • 4 key points
  • Code examples
Test yourself

What interviewers test in Core Java

Core Java rounds check whether you understand the language model: objects and references, immutability, how exceptions flow and how the main collections behave. Expect a definition question followed by “why?” or “what happens if…?”.

  • OOP in practiceExplain the four pillars with one connected example, not four separate definitions.
  • Strings and memoryString pool, immutability and when to use StringBuilder.
  • ExceptionsChecked vs unchecked, try-with-resources and custom exceptions.
  • CollectionsArrayList vs LinkedList, HashMap internals, equals/hashCode contract.

Core Java questions come up in almost every fresher interview for Java, Android and backend roles. Interviewers rarely want textbook definitions; they want to see that you understand why Java works the way it does. Each answer below is written the way you would explain it in an interview, with a short example.

1. What are the four pillars of OOP? Explain with a Java example.

Encapsulation keeps data private and exposes it through methods. Inheritance lets a class reuse another class’s behaviour. Polymorphism lets one call behave differently depending on the object. Abstraction hides details behind a simple interface.

In an interview, give one example that shows all four together, such as a payment system:

abstract class Payment {                 // abstraction
    private double amount;               // encapsulation
    Payment(double amount) { this.amount = amount; }
    double getAmount() { return amount; }
    abstract void pay();
}

class UpiPayment extends Payment {       // inheritance
    UpiPayment(double a) { super(a); }
    void pay() { System.out.println("Paid " + getAmount() + " via UPI"); }
}

Payment p = new UpiPayment(499);
p.pay();                                 // polymorphism: UpiPayment.pay() runs

2. What is the difference between == and equals()?

== compares references for objects (are both variables pointing to the same object?) and values for primitives. equals() compares the contents, as defined by the class. String, wrapper classes and most collections override equals() to compare values.

String a = new String("java");
String b = new String("java");
System.out.println(a == b);      // false – different objects
System.out.println(a.equals(b)); // true  – same characters

3. Why is String immutable in Java?

Once a String object is created, its value cannot change; any “modification” creates a new object. Java does this for four reasons:

  • String pool: many variables can safely share one literal.
  • Security: file paths, URLs and class names cannot be changed after validation.
  • Thread safety: immutable objects can be shared without synchronisation.
  • Hash caching: the hash code is computed once, which makes String fast as a HashMap key.

For many changes in a loop, use StringBuilder.


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

String is immutable. StringBuilder is mutable and fast but not thread-safe. StringBuffer is mutable and thread-safe because its methods are synchronised, which makes it slower. In practice, use StringBuilder unless several threads modify the same object.

StringBuilder sb = new StringBuilder();
for (int i = 1; i <= 3; i++) {
    sb.append(i).append(',');
}
System.out.println(sb);   // 1,2,3,

5. What is the difference between an abstract class and an interface?

An abstract class can have state (fields), constructors and both abstract and concrete methods; a class can extend only one. An interface defines a contract; since Java 8 it can have default and static methods, but no instance fields, and a class can implement many.

Use an abstract class for closely related classes that share code (e.g. Vehicle), and an interface for a capability that unrelated classes can have (e.g. Comparable, Runnable).


6. What is the difference between overloading and overriding?

Overloading: same method name, different parameter lists, in the same class; resolved at compile time. Overriding: a subclass provides its own version of a parent method with the same signature; resolved at runtime, which is how polymorphism works.

class Printer {
    void print(int x)    { System.out.println("int " + x); }
    void print(String s) { System.out.println("text " + s); }  // overloading
}
class ColorPrinter extends Printer {
    @Override
    void print(String s) { System.out.println("color " + s); } // overriding
}

7. What is the difference between checked and unchecked exceptions?

Checked exceptions (subclasses of Exception but not RuntimeException, such as IOException) must be caught or declared with throws; they represent recoverable situations outside the program’s control. Unchecked exceptions (RuntimeException and its subclasses, such as NullPointerException) usually indicate programming errors and do not need to be declared.

try (BufferedReader r = new BufferedReader(new FileReader("data.txt"))) {
    System.out.println(r.readLine());
} catch (IOException e) {          // checked: compiler forces handling
    System.out.println("Could not read file");
}

8. What is the difference between final, finally and finalize?

final is a keyword: a final variable cannot be reassigned, a final method cannot be overridden and a final class cannot be extended. finally is a block that runs after try/catch whether or not an exception occurs, used for cleanup. finalize() was a method called by the garbage collector before removing an object; it is deprecated and should not be used — use try-with-resources instead.


9. What is the difference between ArrayList and LinkedList?

ArrayList is backed by a dynamic array: fast random access (get(i) is O(1)), but inserting or removing in the middle shifts elements. LinkedList is a doubly linked list: fast insertion and removal at known positions, but get(i) is O(n). In most real code ArrayList is faster because of better memory locality, so it is the default choice.


10. How does HashMap work internally?

A HashMap stores entries in an array of buckets. For put(key, value), Java computes key.hashCode(), mixes the bits and uses them to pick a bucket. If two keys land in the same bucket (a collision), entries are kept in a linked list; since Java 8, a bucket with many entries becomes a balanced tree, so lookups stay fast. get() finds the bucket, then uses equals() to find the exact key. When the map is 75% full (load factor 0.75), it doubles its capacity and rehashes.

That is why keys must implement hashCode() and equals() consistently.


Remember

Key points

  • == vs equals()

    == compares references for objects; equals() compares contents when the class overrides it.

  • String is immutable

    Every change creates a new object; use StringBuilder in loops.

  • One class, many interfaces

    Java allows single inheritance of classes but multiple interfaces.

  • equals and hashCode together

    Objects that are equal must return the same hashCode, or HashMap lookups fail.

Interview drill

Follow-up questions

What the interviewer asks after your first answer. Turn on practice mode, answer each one aloud, then reveal.

  1. 1 What happens if you override equals() but not hashCode()? Intermediate

    Two objects that are equal may produce different hash codes, so HashMap and HashSet will put them in different buckets. A lookup with an “equal” key may then fail to find the stored value, and a set may contain duplicates.

    Set<Student> s = new HashSet<>();
    s.add(new Student("Asha", 1));
    s.contains(new Student("Asha", 1)); // false if hashCode() not overridden

    Key insight: The contract: if a.equals(b) is true, a.hashCode() must equal b.hashCode().

  2. 2 Can we override a static method? Basic

    No. Static methods belong to the class, not to objects, so they are resolved at compile time. A subclass can declare a static method with the same signature, but that hides the parent method rather than overriding it.

    Key insight: Method hiding uses the reference type; overriding uses the object type.

  3. 3 Why is the main method static? Basic

    The JVM must call main before any object of the class exists. Making it static lets the JVM call it using the class name, without creating an instance.

    Key insight: Static means “belongs to the class” — available without an object.

  4. 4 What is the difference between fail-fast and fail-safe iterators? Advanced

    Fail-fast iterators (from ArrayList, HashMap) throw ConcurrentModificationException if the collection is structurally modified during iteration, except through the iterator itself. Fail-safe iterators (from CopyOnWriteArrayList, ConcurrentHashMap) work on a copy or a weakly consistent view, so they do not throw but may not show the latest changes.

    List<Integer> list = new ArrayList<>(List.of(1, 2, 3));
    for (Integer x : list) {
        if (x == 2) list.remove(x);   // ConcurrentModificationException
    }
    list.removeIf(x -> x == 2);       // correct way

    Key insight: Use iterator.remove() or removeIf() to delete while iterating.

  5. 5 Can a constructor be private? Why would you do that? Intermediate

    Yes. A private constructor stops other classes from creating objects directly. It is used in the Singleton pattern, in utility classes with only static methods (like Math), and with static factory methods.

    public final class AppConfig {
        private static final AppConfig INSTANCE = new AppConfig();
        private AppConfig() { }
        public static AppConfig get() { return INSTANCE; }
    }

    Key insight: Private constructor + static accessor = controlled object creation.

  6. 6 What is the difference between Comparable and Comparator? Intermediate

    Comparable defines a class’s natural order through compareTo() inside the class itself. Comparator defines an external order, so you can sort the same objects in different ways without changing the class.

    students.sort(Comparator.comparing(Student::getMarks).reversed()
                            .thenComparing(Student::getName));

    Key insight: One natural order (Comparable), any number of custom orders (Comparator).

Preparing with friends?

Share this page with your study group or placement batch.

Search LearnFrenzy

Esc

Quick links