Common interview questions on Java SE fundamentals — language features, OOP principles, and core APIs.

OOP Principles

Q: Explain the four pillars of OOP.

Pillar Description Java example
Encapsulation Hide internal state, expose via methods Private fields + getters/setters
Inheritance Reuse behavior from parent class class Dog extends Animal
Polymorphism Same interface, different behavior Method overriding, interfaces
Abstraction Hide complexity, show essentials Abstract classes, interfaces

Q: Difference between abstract class and interface?

Abstract class Interface
Fields Any type public static final only
Methods Abstract + concrete Abstract + default + static
Inheritance Single (extends) Multiple (implements)
Constructor Yes No
Use when Shared state/behavior Capability contract

Since Java 8, interfaces can have default and static methods, narrowing the gap.

equals() and hashCode()

Q: Why must equals() and hashCode() be consistent?

If two objects are equal (equals() returns true), they must have the same hash code. Violating this breaks HashMap and HashSet:

  Map<Key, String> map = new HashMap<>();
Key k1 = new Key("abc");
Key k2 = new Key("abc");
map.put(k1, "value");
map.get(k2);  // null if hashCode() inconsistent!
  

Q: Implement equals() and hashCode() correctly.

  @Override
public boolean equals(Object o) {
    if (this == o) return true;
    if (!(o instanceof Person person)) return false;
    return Objects.equals(name, person.name) && age == person.age;
}

@Override
public int hashCode() {
    return Objects.hash(name, age);
}
  

String Immutability

Q: Why is String immutable in Java?

  1. String pool — interning requires immutability
  2. Security — class names, file paths, network connections use strings
  3. Thread safety — immutable objects are inherently thread-safe
  4. Hash code caching — computed once, cached forever

Q: String vs StringBuilder vs StringBuffer?

String StringBuilder StringBuffer
Mutable No Yes Yes
Thread-safe Yes (immutable) No Yes (synchronized)
Performance Slow for concat Fast Slower than Builder

Exception Handling

Q: Checked vs unchecked exceptions?

Checked Unchecked
Parent Exception (not RuntimeException) RuntimeException
Compile-time Must handle or declare Optional
Examples IOException, SQLException NullPointerException, IllegalArgumentException
When to use Recoverable conditions Programming errors

Q: try-with-resources?

  try (BufferedReader reader = Files.newBufferedReader(path)) {
    return reader.readLine();
}  // reader.close() called automatically, even on exception
  

Requires resource to implement AutoCloseable.

Java 8+ Features

Q: Explain Lambda expressions and Functional Interfaces.

  // Before
Collections.sort(list, new Comparator<String>() {
    public int compare(String a, String b) { return a.compareTo(b); }
});

// After
Collections.sort(list, (a, b) -> a.compareTo(b));
// or
Collections.sort(list, String::compareTo);
  

A functional interface has exactly one abstract method: Predicate, Function, Consumer, Supplier.

Q: Stream API — intermediate vs terminal operations?

  List<String> result = names.stream()       // source
    .filter(n -> n.startsWith("A"))      // intermediate (lazy)
    .map(String::toUpperCase)              // intermediate (lazy)
    .sorted()                              // intermediate (lazy)
    .collect(Collectors.toList());         // terminal (triggers execution)
  

Common Coding Questions

Q: Reverse a string without built-in reverse.

  public static String reverse(String s) {
    char[] chars = s.toCharArray();
    for (int i = 0, j = chars.length - 1; i < j; i++, j--) {
        char tmp = chars[i];
        chars[i] = chars[j];
        chars[j] = tmp;
    }
    return new String(chars);
}
  

Q: Find the first non-repeating character.

  public static char firstNonRepeating(String s) {
    Map<Character, Integer> count = new LinkedHashMap<>();
    for (char c : s.toCharArray()) count.merge(c, 1, Integer::sum);
    return count.entrySet().stream()
        .filter(e -> e.getValue() == 1)
        .map(Map.Entry::getKey)
        .findFirst().orElse('\0');
}
  

Best Practices for Interviews

  • Explain trade-offs, not just definitions
  • Use concrete examples from real projects
  • Mention Java version when discussing features (e.g., “since Java 14, switch expressions…”)
  • For coding questions, clarify requirements before coding