Skip to content
Tutorials Center
My learning

Topics

Lesson 18 of 77 ยท Java Interview Questions

Java: OOP, Strings and the Object Contract

Answer Java interview questions on equals and hashCode, immutability, the String pool, interfaces vs abstract classes and records, with runnable stand-ins.

Java interviews start with the core language: the Object contract, String, and the choice between interfaces and abstract classes. The questions are short, but each hides a follow-up ("what happens if you override equals but not hashCode?"), so a precise answer matters.

Real Java cannot run on this page for these examples, so the Java code is read-only. Where behavior can be shown with a stand-in, the runnable examples are small JavaScript models. Each one says what is real Java and what is the stand-in. For the full tutorials see The Object Class, Strings, Immutable Classes, Interfaces and Records.

The Object contract

equals Reflexive, symmetric, transitive, consistent.
hashCode Equal objects must have equal hash codes.
toString A readable description.

Break equals/hashCode and hash-based collections misbehave.

1 / 2

== versus equals

Q: What is the difference between == and equals? For objects, == compares references (are these the same object?). equals compares logical equality, as defined by the class. The default Object.equals is the same as ==, so you must override it for value types. For primitives, == compares values.

Java
String a = new String("hi");
String b = new String("hi");
System.out.println(a == b);       // false: two different objects
System.out.println(a.equals(b));  // true: same characters

equals and hashCode

Q: Why must you override hashCode when you override equals? The contract says: if a.equals(b) is true, then a.hashCode() == b.hashCode(). Hash-based collections (HashMap, HashSet) use the hash to pick a bucket and then call equals inside that bucket. If two equal objects have different hashes, they land in different buckets, so lookups fail even though the object is "there".

The reverse is not required: unequal objects may share a hash (a collision). A constant hash is legal but turns the table into a list.

Java
final class Point {
    private final int x, y;
    Point(int x, int y) { this.x = x; this.y = y; }

    @Override public boolean equals(Object o) {
        if (this == o) return true;
        if (!(o instanceof Point p)) return false;
        return x == p.x && y == p.y;
    }

    @Override public int hashCode() {
        return java.util.Objects.hash(x, y);
    }
}

The next TryIt is a stand-in written in JavaScript. It models a hash set with buckets so you can see what breaks. The real Java classes differ in details, but the lookup logic (hash, then bucket, then equals) is the same idea.

JS Stand-in: a hash set with and without a matching hashCode

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Follow-up: "Is it safe to use a mutable field in hashCode?" No. If a key's hash changes after insertion, the entry sits in the wrong bucket and cannot be found. Use immutable keys.

Immutability

Q: How do you make a class immutable? Make the class final (or all constructors private), make all fields private final, set no setters, do not leak mutable internals (copy mutable arguments in, return copies or unmodifiable views out), and never let this escape from the constructor. Benefits: thread-safety without locks, safe sharing, safe use as map keys, and cacheable hash codes.

Java
public final class Appointment {
    private final String title;
    private final java.util.List<String> guests;

    public Appointment(String title, java.util.List<String> guests) {
        this.title = title;
        this.guests = java.util.List.copyOf(guests);  // defensive copy
    }

    public java.util.List<String> guests() { return guests; } // already immutable
}

The String pool

Q: What is the String pool, and why is String immutable? String literals are stored in a shared pool inside the heap, so identical literals refer to the same object. new String("x") always creates a separate object, and intern() returns the pooled one. String is immutable because the pool relies on sharing, because its hash code can be cached (it is a favorite map key), and because security-sensitive values (class names, paths) cannot be altered after validation.

Java
String s1 = "java";
String s2 = "java";
String s3 = new String("java");
System.out.println(s1 == s2);            // true: same pooled object
System.out.println(s1 == s3);            // false
System.out.println(s1 == s3.intern());   // true
JS Stand-in: an interning pool

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Q: String versus StringBuilder versus StringBuffer? String is immutable. StringBuilder is a mutable buffer for building text, not synchronized, and the right default. StringBuffer is the older synchronized version, rarely needed. Concatenating in a loop with += creates many temporary strings: use StringBuilder.

Interface or abstract class?

Q: When do you use each?

Interface Abstract class
Inheritance A class can implement many A class extends only one
State No instance fields (only constants) Can have fields and constructors
Methods Abstract, default, static, private Abstract and concrete, any access
Best for A capability or contract (Comparable, Runnable) A shared base with common state and code

Since Java 8, interfaces can have default methods, which narrowed the gap, but they still cannot hold instance state. Prefer interfaces for contracts and add an abstract class only when subclasses truly share fields or construction logic.

Java
interface Shape { double area(); default String describe() { return "area " + area(); } }

abstract class Vehicle {
    protected final String plate;
    Vehicle(String plate) { this.plate = plate; }
    abstract int wheels();
}

Records

Q: What is a record? A concise, shallowly immutable data carrier (Java 16+). The compiler generates the constructor, accessors, equals, hashCode and toString from the components. Records are implicitly final and cannot extend a class, but they can implement interfaces and have compact constructors for validation.

Java
public record Point(int x, int y) {
    public Point {
        if (x < 0 || y < 0) throw new IllegalArgumentException("negative");
    }
}
// new Point(1, 2).equals(new Point(1, 2)) is true, hashCodes match

"Shallowly" matters: a record holding a List still exposes a mutable list unless you copy it.

More Java fundamentals: wrapper classes, marker interfaces, covariant returns, jagged arrays and I/O streams

The questions above are the core. These five are the "small topics" that fill a long Java screening. Unlike the stand-ins earlier in this lesson, the examples in this section are real Java: they run on the site's Java 25 runner.

Wrapper classes, autoboxing and the Integer cache

Q: What are wrapper classes? Each primitive has an object twin: int has Integer, double has Double, boolean has Boolean, and so on (char has Character). Collections and generics only hold objects (List<int> is illegal, List<Integer> is fine), so the wrappers exist to put primitives into them. Autoboxing converts int to Integer automatically; unboxing does the reverse.

The classic follow-ups:

  • == on wrappers compares references. Integer.valueOf caches objects for values from -128 to 127, so == happens to work for small numbers and fails for large ones. Always compare wrappers with equals.
  • Unboxing null throws NullPointerException. Integer count = map.get(key); int n = count; crashes when the key is missing.
  • Boxing in a loop is slow. Long sum = 0L; sum += i; allocates an object per iteration.
  • Wrappers are immutable, like String.
Java Real Java: the Integer cache and the unboxing trap

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Marker interfaces

A marker interface has no methods. Implementing it tags a class so that other code can check instanceof and treat it differently. The classics are java.io.Serializable (the object may be turned into bytes), Cloneable (Object.clone() may copy it field by field) and java.util.RandomAccess (the list has fast indexed access, so algorithms may loop by index). If you call clone() on a class that does not implement Cloneable, you get CloneNotSupportedException.

Today annotations (@FunctionalInterface, custom runtime annotations) often do the same job, and they carry parameters and can target methods and fields. The remaining advantage of a marker interface is that it is a type: you can write a method parameter as Serializable and the compiler checks it. sealed interfaces (Java 17+) are the modern way to say "only these classes may implement me".

Covariant return types

Q: Can an overriding method return a different type? Yes, since Java 5, if the new return type is a subtype of the original (a covariant return). It lets a subclass return its own more specific type, so callers do not need a cast. It only applies to reference types; a primitive return type must match exactly. Typical uses: clone(), builders and fluent APIs, and factory methods.

Java Real Java: a covariant return and a marker interface

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Jagged arrays

A Java multidimensional array is an array of arrays, so the rows do not have to be the same length. That is a jagged (ragged) array. Create the outer array with only the first dimension (new int[3][]), then allocate each row. It saves memory for triangular data (Pascal's triangle, adjacency lists) and is why matrix[i].length can differ per row. Arrays.toString prints one level; use Arrays.deepToString for nested arrays.

Java Real Java: Pascal's triangle in a jagged array

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

I/O streams: bytes versus characters

Q: What is the difference between InputStream and Reader? The java.io classes come in two families. Byte streams (InputStream, OutputStream) move raw bytes: images, zip files, network data. Character streams (Reader, Writer) move text, and they convert between bytes and characters using a charset. The bridge is InputStreamReader and OutputStreamWriter. Do not rely on the platform default charset: pass StandardCharsets.UTF_8, because one character can be several bytes (รฉ is two bytes in UTF-8, so the byte count and the character count differ).

Other points interviewers expect:

  • Decorators: BufferedReader and BufferedInputStream wrap another stream and cut the number of expensive reads. DataOutputStream writes primitives; ObjectOutputStream writes serializable objects (Serializable is the marker interface from above).
  • try-with-resources closes anything that implements AutoCloseable automatically, in reverse order, even when an exception is thrown. Prefer it to finally { close(); }.
  • java.nio.file: Files.readAllLines, Files.writeString, Files.lines (a lazy stream that must be closed) and Path are the modern API for files; the old File class is mostly legacy. System.in, System.out and System.err are the standard streams.
Java Real Java: bytes, characters, buffering and try-with-resources

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Two objects are equal according to equals, but have different hashCode values. What can go wrong?

    Hash collections look in the bucket chosen by the hash. Equal objects with different hashes usually land in different buckets.
  2. 2. What does == compare for two String objects?

    == on objects compares references. Use equals for text content.
  3. 3. Which feature can an interface NOT have?

    Interface fields are implicitly public static final constants. Per-instance state needs a class.
  4. 4. Which statement about records is true?

    Records are final, implement interfaces freely, and have shallowly immutable components.

Summary

  • == compares references; equals compares logical value; override both equals and hashCode together.
  • Equal objects must share a hash code; keys should be immutable.
  • Immutable class recipe: final class, private final fields, defensive copies, no setters.
  • Literals share one pooled String; new String makes a new object; intern() returns the pooled one.
  • Interfaces are contracts without instance state; abstract classes share state and code; records are compact immutable data carriers.
  • Wrapper classes box primitives for collections; compare them with equals (the Integer cache makes == work only from -128 to 127) and beware unboxing null.
  • Marker interfaces tag a class without methods, covariant returns let an override return a subtype, and jagged arrays are arrays of arrays with rows of different lengths.
  • Byte streams move bytes and character streams convert with a charset; wrap with buffered decorators and close with try-with-resources.

Next: Java: Collections and HashMap Internals.