Skip to the content

Lesson 288 of 296

Java exceptions, memory and interview questions

What you will learn

  • Checked and unchecked exceptions
  • try, catch, finally and try-with-resources
  • String immutability, == vs equals and StringBuilder
  • Stack, heap and garbage collection
  • Threads basics
  • Classic Java interview questions and a problem in Java
On this page

Exceptions

Java exceptions work like TypeScript's throw and catch, with one big difference: checked exceptions.

KindExamplesRule
CheckedIOException, SQLExceptionThe compiler forces you to catch it or declare it with throws
Unchecked (RuntimeException)NullPointerException, IllegalArgumentException, IndexOutOfBoundsExceptionNot forced; usually programming errors
ErrorOutOfMemoryError, StackOverflowErrorSerious JVM problems; do not catch
Java
import java.io.*;
import java.nio.file.*;

public class ExceptionsDemo {
    static class InsufficientFundsException extends RuntimeException {
        InsufficientFundsException(String message) { super(message); }
    }

    static void withdraw(double balance, double amount) {
        if (amount > balance) throw new InsufficientFundsException("Balance too low");
    }

    static String firstLine(Path path) throws IOException {      // checked: must declare
        try (BufferedReader reader = Files.newBufferedReader(path)) {  // try-with-resources
            return reader.readLine();
        }                                                         // reader is closed automatically
    }

    public static void main(String[] args) throws IOException {
        try {
            withdraw(10, 50);
        } catch (InsufficientFundsException e) {
            System.out.println("Caught: " + e.getMessage());
        } finally {
            System.out.println("finally always runs");
        }

        Path file = Files.writeString(Path.of("demo.txt"), "first line\nsecond");
        System.out.println(firstLine(file));                      // first line
    }
}

try-with-resources closes anything that implements AutoCloseable (files, database connections), even on errors. It is Java's version of Python's with.

Do not catch Exception and do nothing ("swallowing"); you hide bugs (Lesson 266).

String immutability, == vs equals and StringBuilder

Java
public class StringTraps {
    public static void main(String[] args) {
        String a = "hello";
        String b = "hello";
        String c = new String("hello");
        System.out.println(a == b);          // true  (same object from the string pool)
        System.out.println(a == c);          // false (different object)
        System.out.println(a.equals(c));     // true  (same characters)

        String s = "x";
        s.toUpperCase();                     // returns a NEW string; s is unchanged
        System.out.println(s);               // x

        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < 5; i++) sb.append(i);   // efficient in loops
        System.out.println(sb.reverse());    // 43210
    }
}
  • Strings are immutable: methods return new strings.
  • == compares references; .equals() compares content. Always use .equals().
  • String + inside a loop creates many objects; use StringBuilder.

Stack, heap and garbage collection

  • The stack holds each method call's local variables: primitives and references. It is cleared when the method returns.
  • The heap holds objects created with new.
  • The garbage collector (GC) automatically frees heap objects that nothing references any more. You never call free.
  • Memory leaks can still happen: for example, a static list or cache that keeps growing and keeps references forever.
  • StackOverflowError: too-deep recursion. OutOfMemoryError: the heap is full.

Java passes everything by value. For objects, the value passed is the reference: a method can change the object's fields, but reassigning the parameter does not affect the caller.

Threads basics

Java has real parallel threads. The basics interviewers ask:

  • Do not create raw threads by hand for tasks; use an ExecutorService (thread pool).
  • Shared mutable data needs protection: synchronized, locks, or thread-safe classes like ConcurrentHashMap and AtomicInteger.
  • Java 21 added virtual threads: very lightweight threads that make it cheap to handle many waiting tasks, such as HTTP requests.
Java
import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicInteger;

public class ThreadsDemo {
    public static void main(String[] args) throws InterruptedException {
        AtomicInteger counter = new AtomicInteger();
        try (ExecutorService pool = Executors.newVirtualThreadPerTaskExecutor()) {
            for (int i = 0; i < 1000; i++) {
                pool.submit(counter::incrementAndGet);
            }
        }                                          // waits for all tasks to finish
        System.out.println(counter.get());         // 1000
    }
}

With a plain int and count++ from many threads, the result would often be less than 1000, because count++ is a read, an add and a write: a race condition, the same "lost update" problem as in databases (Lesson 224).

Classic Java interview questions

QuestionShort answer
JDK vs JRE vs JVM?Development kit / runtime / the engine that runs bytecode
== vs equals?References vs content; override equals and hashCode together
Why is String immutable?Safety (keys, security), thread safety and the string pool
String vs StringBuilder?Immutable vs mutable; use StringBuilder for building in loops
ArrayList vs LinkedList?Array-backed fast index access vs nodes; ArrayList is almost always better
HashMap internals?An array of buckets; the key's hashCode picks the bucket; equals finds the key; large buckets turn into trees
Checked vs unchecked exceptions?Compiler-forced vs RuntimeException
final, finally, finalize?Cannot change / always-run block / an old, deprecated cleanup hook: do not use
Abstract class vs interface?Shared state and one parent vs contracts and many
Is Java pass-by-reference?No. Always by value; object references are copied

A problem in Java

Two sum with a HashMap, the same idea as in TypeScript (Lesson 122) and Python (Lesson 284):

Java
import java.util.*;

public class TwoSum {
    static int[] twoSum(int[] nums, int target) {
        Map<Integer, Integer> seen = new HashMap<>();   // value -> index
        for (int i = 0; i < nums.length; i++) {
            Integer j = seen.get(target - nums[i]);
            if (j != null) return new int[] { j, i };
            seen.put(nums[i], i);
        }
        return new int[0];
    }

    public static void main(String[] args) {
        System.out.println(Arrays.toString(twoSum(new int[] {2, 7, 11, 15}, 9)));  // [0, 1]
    }
}

How to say it in an interview

"Java has checked exceptions the compiler forces you to handle, and unchecked RuntimeExceptions for programming errors. I use try-with-resources so files and connections always close. Strings are immutable, so I compare with equals and build in loops with StringBuilder. Objects live on the heap and are freed by the garbage collector, while locals and references live on the stack; Java always passes by value, with references copied for objects. For concurrency I use an ExecutorService, virtual threads for many waiting tasks, and thread-safe classes like AtomicInteger and ConcurrentHashMap instead of unprotected shared state."

Key words

WordMeaning
Checked exceptionMust be caught or declared with throws
try-with-resourcesAutomatically closes resources after the block
String poolJava reuses identical string literals
StringBuilderA mutable class for building strings efficiently
Heap / stackWhere objects live / where method locals live
Garbage collectorFrees objects that are no longer referenced
Virtual threadA lightweight thread from Java 21 for many waiting tasks

Now prove it

This lesson is complete when you pass the quiz and all three practice levels.