LearnFrenzy
Sign in Take a free test

Java Programming interview · Set 9 of 13

Java Strings, Exceptions and Generics

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

Everyday Java, done correctly

Strings test memory knowledge, exceptions test design, generics test type safety. Give the rule, a small example, and the mistake it prevents.

  • StringsPool, intern, equals and builders.
  • ExceptionsChecked vs unchecked, resources and custom errors.
  • GenericsBounds, wildcards and erasure.

Strings, exceptions and generics appear in every Java code base — and in every Java interview. Interviewers check memory behaviour (the string pool), error-handling design and how generics keep collections type-safe.

1. What is the String pool?

A special area of the heap where Java keeps one copy of each string literal. Literals with the same value share an object; new String("x") always creates a new object outside the pool. intern() returns the pooled copy. That is why == on strings sometimes works by accident — always use equals().

String a = "java";
String b = "java";
String c = new String("java");
System.out.println(a == b);           // true  (same pooled object)
System.out.println(a == c);           // false (new object)
System.out.println(a == c.intern());  // true
System.out.println(a.equals(c));      // true — the correct comparison

2. Checked vs unchecked exceptions?

Checked exceptions (subclasses of Exception except RuntimeException) must be caught or declared — for recoverable conditions such as IOException. Unchecked exceptions (RuntimeException and subclasses) signal programming errors such as NullPointerException or invalid arguments, and need not be declared. Errors (OutOfMemoryError) should not be caught in normal code.


3. How does try-with-resources work?

Any object implementing AutoCloseable declared in the try header is closed automatically, in reverse order, even when an exception is thrown. If closing also throws, that exception is attached to the main one as a suppressed exception instead of hiding it.

try (var reader = Files.newBufferedReader(Path.of("marks.csv"));
     var writer = Files.newBufferedWriter(Path.of("report.txt"))) {
    String line;
    while ((line = reader.readLine()) != null) {
        writer.write(line.toUpperCase());
        writer.newLine();
    }
}   // both closed here, even on error

4. How should you design custom exceptions?

Create exceptions that describe the business problem (InsufficientBalanceException), extend RuntimeException for most application errors, keep the original cause when wrapping, and include useful context in the message. Do not use exceptions for normal control flow.

public class InsufficientBalanceException extends RuntimeException {
    private final BigDecimal shortfall;
    public InsufficientBalanceException(BigDecimal shortfall) {
        super("Balance short by " + shortfall);
        this.shortfall = shortfall;
    }
    public BigDecimal shortfall() { return shortfall; }
}

try {
    gateway.charge(order);
} catch (IOException e) {
    throw new PaymentFailedException("Gateway unreachable for order " + order.id(), e);   // keep the cause
}

5. What is the difference between throw and throws, and final, finally and finalize?

throw raises an exception; throws declares that a method may raise one. final is a modifier; finally is a block that always runs after try/catch; finalize() was a GC hook, deprecated and removed from use — use try-with-resources or Cleaner instead.


6. Why do we need generics?

Generics give compile-time type safety and remove casts: List<String> cannot accidentally hold an Integer, and reading needs no cast. You can write generic methods and classes that work for any type while staying safe.

public static <T extends Comparable<T>> T max(List<T> items) {
    T best = items.get(0);
    for (T item : items) if (item.compareTo(best) > 0) best = item;
    return best;
}
max(List.of(3, 9, 4));          // 9
max(List.of("pear", "apple"));  // "pear"

7. Explain wildcards and PECS.

? extends T means “some subtype of T” — you can read Ts from it (a producer). ? super T means “some supertype of T” — you can add Ts to it (a consumer). Remember PECS: Producer Extends, Consumer Super, as in Collections.copy(List<? super T> dest, List<? extends T> src).

double sum(List<? extends Number> nums) {          // reads Numbers: producer
    double total = 0;
    for (Number n : nums) total += n.doubleValue();
    return total;
}
void addDefaults(List<? super Integer> target) {    // writes Integers: consumer
    target.add(0);
    target.add(1);
}

8. What is type erasure?

Generic type information exists only at compile time; the compiler checks types and then erases them, so at runtime List<String> and List<Integer> are both just List. Consequences: you cannot do new T(), instanceof List<String> or create generic arrays directly, and overloading on generic types alone is not allowed.


Remember

Key points

  • equals() for strings

    == compares references.

  • try-with-resources

    Closes everything, keeps suppressed errors.

  • Wrap with the cause

    Never lose the original exception.

  • PECS

    Producer extends, consumer super.

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 How many objects does new String("hello") create? Intermediate

    Up to two: the literal in the pool (if not already there) and the new object on the heap.

  2. 2 Can a finally block be skipped? Intermediate

    Only if the JVM exits (System.exit), crashes or the thread is killed. A return in try still runs finally first.

  3. 3 What is multi-catch? Basic

    Catching several unrelated exceptions in one block: catch (IOException | SQLException e).

  4. 4 Why can't you create a generic array like new T[10]? Advanced

    Because of erasure the runtime does not know T, and arrays need their component type at runtime. Use a List, or pass a Class<T> and use Array.newInstance.

  5. 5 What is the difference between String.valueOf(obj) and obj.toString()? Basic

    String.valueOf(null) returns "null"; calling toString() on null throws NullPointerException.

  6. 6 Should you catch NullPointerException? Basic

    No — fix the cause. Validate inputs with Objects.requireNonNull, use Optional for absent results, and rely on helpful NPE messages to find bugs.

Preparing with friends?

Share this page with your study group or placement batch.

Popular