Gapfyre

Java interview questions

The Java questions that come up again and again are the ones that sound simple: == against .equals(), checked against unchecked exceptions, what final really fixes in place. A confident answer to each is worth more than a memorised definition.

This set covers those, plus streams, Optional, try-with-resources, what the JVM still knows about a List<String> at run time, and how the JDK, JRE and JVM fit together.

All 16 are the free Foundation level of the Java & JVM topic in GapfyreSWE. Try each one before you open its answer.

  1. What is the difference between == and .equals() in Java?

    1. .equals() compares references; == compares content
    2. == is only for primitives; .equals() is only for collections
    3. == compares references; .equals() compares content
    4. They are interchangeable — both compare content for all types
    Show the answer

    C. == compares references; .equals() compares content

    == compares object references (memory addresses) for objects, and primitive values for primitives. .equals() compares object content/value as defined by the class. Two distinct String objects with the same text will return false for == but true for .equals().

  2. What is autoboxing in Java?

    1. A JVM optimisation that inlines small method calls
    2. Serialising Java objects to a binary format automatically
    3. Automatically packing multiple values into an array
    4. Automatic conversion between primitives and wrapper classes
    Show the answer

    D. Automatic conversion between primitives and wrapper classes

    Autoboxing is the automatic conversion of a primitive type (e.g., int) to its corresponding wrapper class (e.g., Integer) when needed. Unboxing is the reverse. This lets primitives be used in contexts requiring objects, like collections.

  3. What is the difference between a checked and an unchecked exception in Java?

    1. Checked exceptions crash the JVM; unchecked exceptions are recoverable
    2. Unchecked exceptions are checked at runtime; checked exceptions are optimised away
    3. Checked exceptions must be caught or declared at compile time; unchecked exceptions do not
    4. They are identical — the distinction was removed in Java 8
    Show the answer

    C. Checked exceptions must be caught or declared at compile time; unchecked exceptions do not

    Checked exceptions (subclasses of Exception but not RuntimeException) must be either caught or declared with throws — the compiler enforces this. Unchecked exceptions (RuntimeException and its subclasses) do not require explicit handling.

  4. What does the final keyword mean when applied to a variable in Java?

    1. The variable is garbage collected immediately when the method returns
    2. The variable is thread-safe and can be shared without synchronisation
    3. It can be assigned once and not changed afterwards
    4. The variable is stored on the heap rather than the stack
    Show the answer

    C. It can be assigned once and not changed afterwards

    A final variable can only be assigned once. For primitives, the value cannot change. For object references, the reference cannot be reassigned, but the object itself can still be mutated (unless the object is also immutable).

  5. What is the purpose of the Java Stream API introduced in Java 8?

    1. To read and write bytes from files and network sockets
    2. To provide a reactive programming model for asynchronous event streams
    3. Functional pipelines over sequences: filter, map, reduce
    4. To stream large objects from the heap to disk to free memory
    Show the answer

    C. Functional pipelines over sequences: filter, map, reduce

    The Stream API provides a functional, declarative approach to processing sequences of elements, with each pipeline step usually supplied as a lambda expression. Streams support pipeline operations (filter, map, reduce) that can be run lazily and, in some cases, in parallel (parallelStream()). They do not store data; they process it from a source such as a Collection or an I/O channel.

  6. What does Java's Optional<T> class help prevent?

    1. NullPointerException, by making absence explicit in the type
    2. ConcurrentModificationException when iterating and modifying a collection
    3. StackOverflowError by limiting the depth of Optional chains
    4. ClassCastException when casting between incompatible types
    Show the answer

    A. NullPointerException, by making absence explicit in the type

    Optional<T> is a container that may or may not hold a non-null value. It makes the possibility of an absent value explicit in the API, encouraging callers to handle the empty case instead of assuming a non-null return. This helps prevent NullPointerExceptions by removing the need to return null from methods.

  7. What is the difference between stack memory and heap memory in the JVM?

    1. Heap memory is reclaimed at method return; stack memory is managed by the GC
    2. They refer to the same memory region — "stack" and "heap" are just different allocation strategies
    3. Stack memory stores objects; heap memory stores primitive values and method frames
    4. Stack memory is per-thread and holds frames/locals; heap is shared and holds all object instances
    Show the answer

    D. Stack memory is per-thread and holds frames/locals; heap is shared and holds all object instances

    Each thread has its own stack, which stores stack frames for method calls, local variables, and references. The heap is shared by all threads and holds all objects and class instances. Stack allocation and deallocation is automatic (LIFO) and very fast; heap memory is reclaimed by garbage collection, performed by the JVM's garbage collector. Primitives declared inside methods live on the stack; objects always live on the heap.

  8. What is the purpose of try-with-resources in Java?

    1. It retries the try block if an exception is thrown
    2. It allocates resources from a pool and returns them after use
    3. It closes AutoCloseable resources when the block exits
    4. It converts checked exceptions into unchecked ones
    Show the answer

    C. It closes AutoCloseable resources when the block exits

    try-with-resources (Java 7+) automatically closes any resource that implements AutoCloseable when the try block exits, whether normally or via an exception. This eliminates verbose finally blocks needed to close streams, connections, or file handles and prevents resource leaks.

  9. In the Java Stream API, what is the difference between intermediate and terminal operations?

    1. Terminal operations can be chained; intermediate operations cannot
    2. Intermediate operations execute immediately; terminal operations are deferred
    3. The distinction only applies to parallel streams, not sequential ones
    4. Intermediate ops are lazy and return a Stream; terminal ops run it
    Show the answer

    D. Intermediate ops are lazy and return a Stream; terminal ops run it

    Intermediate operations (e.g. filter, map, sorted) are lazy — they return a new Stream and do not execute until a terminal operation is called. Terminal operations (e.g. collect, forEach, count, findFirst) trigger the pipeline to execute and produce a result or side-effect. A stream can only be consumed by one terminal operation.

  10. Java interfaces can carry default method bodies. What problem was that added to solve?

    1. Allowing an interface to hold state, which is what previously forced the use of abstract classes
    2. Giving Java multiple inheritance of implementation, which had been deliberately excluded before
    3. Adding methods to a published interface without breaking every existing implementer
    4. Letting an interface be instantiated directly when every method has a body
    Show the answer

    C. Adding methods to a published interface without breaking every existing implementer

    Extending an existing interface without breaking every class that implements it. Adding an abstract method to a published interface breaks every implementer at compile time, which made it effectively impossible to evolve one — and Java 8 needed to add stream() to Collection. A default body means existing implementers inherit it and keep compiling. It is an evolution mechanism rather than an invitation to put logic in interfaces, and an interface still cannot hold instance state.

  11. Java strings are immutable. What does that buy, and what does it cost?

    1. Thread safety through internal locking; the cost is contention when many threads read one string
    2. Compact storage, since identical strings are deduplicated; the cost is a slower equals comparison
    3. Faster concatenation, since the compiler can fuse operations; the cost is higher memory use
    4. Safe sharing, stable hash codes and interning; the cost is an allocation per change, hence StringBuilder
    Show the answer

    D. Safe sharing, stable hash codes and interning; the cost is an allocation per change, hence StringBuilder

    It buys safe sharing — a string can be passed anywhere and cached, used as a HashMap key without its hash changing underneath, and interned so identical literals share one object — and it removes a whole class of defensive copying. It costs an allocation for every modification, which is why building a string in a loop with += is quadratic and why StringBuilder exists. The cost is only visible in loops; for ordinary use the sharing is worth far more.

  12. What does the JVM know at run time about a List<String>?

    1. The full type, since the JVM stores type arguments in the class file for reflection
    2. The type argument for collections specifically, which the JVM special-cases for performance
    3. Only that it is a List — the type argument is erased after compile-time checking
    4. The type argument only when it was written explicitly rather than inferred by the compiler
    Show the answer

    C. Only that it is a List — the type argument is erased after compile-time checking

    That it is a List. The type argument is erased by the compiler after it has finished checking, so at run time there is one raw List class and no record of the String. That is why you cannot ask a list what it holds, cannot write new T[], and cannot overload two methods that differ only in their type argument. The checking is real and happens at compile time; what is missing is the information at run time, which is the trade Java made to keep generics backward compatible.

  13. What does the package com.example.app; line at the top of a Java file establish?

    1. The class’s fully qualified name, which must match the directory layout and scopes package-private access
    2. The compilation unit, so that every class in one package is compiled into a single class file
    3. The classpath entry the class will be loaded from, which is why it must match the jar name
    4. The module the class belongs to, which decides which other modules can read it at run time
    Show the answer

    A. The class’s fully qualified name, which must match the directory layout and scopes package-private access

    The class’s fully qualified name — com.example.app.Thing — which is what the compiler and the JVM identify it by, and which must match the directory structure under the source root. That name is how it is resolved on the classpath at run time, and it is the unit that package-private access applies to: a member with no modifier is visible to the rest of that package and nowhere else. Two classes with the same simple name in different packages coexist without conflict.

  14. names is ["Al", "Bobby", "Cara"]. Which line completes this, so count is 2 — the names longer than three characters?

    List<String> names = List.of("Al", "Bobby", "Cara");
    long count = names.stream()
        ___
    1. .map(n -> n.length() > 3).count();
    2. .filter(n -> n.length() > 3).limit(1).count();
    3. .filter(n -> n.length() > 3).count();
    4. .count();
    Show the answer

    C. .filter(n -> n.length() > 3).count();

    filter is the only one of these that drops an element: it keeps "Bobby" and "Cara" and lets "Al" fall out, so count() reports 2. map does not drop anything — it replaces each name with the boolean n.length() > 3 and hands all three of them on, so count() still reports 3, which is the shape of the mistake worth recognising: a stream that is mapped is never shorter than the stream that went in. count() with nothing in front of it is the same 3, and the count of the source rather than of anything asked about it. limit(1) does shorten the stream, but to a fixed number rather than to what matches: it stops at the first long name and reports 1, whatever the rest of the list holds.

  15. What is the relationship between the JDK, the JRE and the JVM?

    1. They are three names for one distribution, kept apart only for backwards compatibility
    2. The JVM contains the JRE, which contains the JDK, each one adding a layer of abstraction
    3. The JDK contains the JRE, which contains the JVM: tools, then libraries, then the engine
    4. The JDK compiles to bytecode and the JRE compiles to native code, with the JVM choosing
    Show the answer

    C. The JDK contains the JRE, which contains the JVM: tools, then libraries, then the engine

    They nest. The JVM is the engine that executes bytecode, and it is what makes "write once, run anywhere" true: a .class file is portable because every platform ships its own JVM to run it. The JRE is that engine plus the standard class library an application needs. The JDK is the JRE plus the tools to produce one — javac, the debugger, jar. So compiling wants a JDK and running wants only a JRE, which is why deployment images used to ship the smaller one.

  16. An older codebase keeps one static SimpleDateFormat for every request and passes java.util.Date values around. What goes wrong that java.time fixes?

    1. Date counts months from 1 while java.time counts from 0, so every month comes out one late or early
    2. SimpleDateFormat ignores the default time zone, which java.time reads from the operating system instead
    3. SimpleDateFormat is not thread-safe and Date is mutable; the java.time types are immutable and thread-safe
    4. Date cannot hold times before 1970, so historical dates wrap around to the far future when formatted
    Show the answer

    C. SimpleDateFormat is not thread-safe and Date is mutable; the java.time types are immutable and thread-safe

    SimpleDateFormat keeps its working state in fields, so threads sharing one corrupt each other: eight threads parsing and formatting the same date through one instance produced tens of thousands of wrong results and about a thousand exceptions, where a shared DateTimeFormatter produced none. Date is mutable besides — setTime changes the value under every reference holding it. The java.time types (LocalDate, Instant, DateTimeFormatter) are immutable and thread-safe: plusDays returns a new date rather than changing the old one.

Practise the rest in the app

GapfyreSWE has 30 more Java questions at Intermediate and Advanced level, and over 4,700 across 80+ topics. It works offline and asks for no account.

Download on the App Store Get it on Google Play

More topics