Autocoder

Java Interview Questions and Answers

Last updated 2026-11-19

Core Java interviews rarely reward memorised definitions. Interviewers show you ten lines of code and ask what it prints, then ask why. This page collects the questions that come up again and again in written tests and technical rounds, with the exact output and the reason behind it.

All answers assume Java 17 or later. Where behaviour changed in a recent release, the answer says so. For process and round structure, see how to crack a Java interview.

Java version17 and later
Question count16, easy to hard
Best forFreshers and 1 to 3 years of experience

How to use this page

Read the question, write down your predicted output, and only then read the answer. Most mistakes come from three areas: reference versus value semantics, the order in which Java runs initialisers, and implicit numeric conversions.

Once these are solid, move to the focused pages on Java OOP, Java collections and Java strings.

Java Interview Questions and Answers: questions with worked answers

  1. 1

    What is the difference between the JDK, JRE and JVM?

    easy

    The JVM executes bytecode and provides garbage collection, the class loader and the execution engine. The JRE is the JVM plus the standard class libraries needed to run a program. The JDK is the JRE plus development tools such as javac, jar, jshell and jlink. Since Java 11 Oracle no longer ships a standalone JRE; you run applications on a JDK or on a runtime image built with jlink. Bytecode is platform independent, the JVM is not: each operating system has its own JVM build.

  2. 2

    Is Java pass by value or pass by reference? Predict the output.

    easy

    Java is always pass by value. For objects the value that is copied is the reference, so a method can mutate the object but cannot make the caller variable point somewhere else. The program prints [1, 2, 3]: reassigning the parameter only changes the local copy, so the 99 never reaches the caller.

    java
    import java.util.*;
    public class Main {
        static void change(List<Integer> list) {
            list.add(3);            // mutates the shared object
            list = new ArrayList<>(); // rebinds the local copy only
            list.add(99);
        }
        public static void main(String[] args) {
            List<Integer> a = new ArrayList<>(List.of(1, 2));
            change(a);
            System.out.println(a);  // [1, 2, 3]
        }
    }
  3. 3

    What is the difference between == and equals()? Predict the Integer cache output.

    easy

    For references, == compares identity and equals() compares logical equality when a class overrides it. Integer.valueOf, which autoboxing uses, caches values from -128 to 127, so two boxed 127 values are the same object and two boxed 128 values are not. Always compare boxed numbers with equals().

    java
    Integer a = 127, b = 127;
    Integer c = 128, d = 128;
    System.out.println(a == b);      // true
    System.out.println(c == d);      // false
    System.out.println(c.equals(d)); // true
  4. 4

    What does this print? Explain how finally interacts with return.

    medium

    It prints "finally" and then 1. The return value is computed and saved before finally runs, so later changes to the variable do not affect it. If finally itself contains a return, that return overrides the try value and also swallows any exception, which is why it is considered bad practice.

    java
    static int f() {
        int x = 1;
        try {
            return x;      // value 1 is saved
        } finally {
            x = 2;         // does not change the saved value
            System.out.println("finally");
        }
    }
    public static void main(String[] a) { System.out.println(f()); }
    // finally
    // 1
  5. 5

    In what order do static blocks, instance blocks and constructors run in an inheritance chain?

    medium

    Static initialisers run once when the class is first initialised, parent before child. For each new object, the parent instance initialisers and constructor run first, then the child ones. Instance initialiser blocks run just before the constructor body of the same class, after the super() call returns.

    java
    class A { static { System.out.println("A static"); }
              { System.out.println("A instance"); }
              A() { System.out.println("A ctor"); } }
    class B extends A { static { System.out.println("B static"); }
              { System.out.println("B instance"); }
              B() { System.out.println("B ctor"); } }
    new B();
    // A static, B static, A instance, A ctor, B instance, B ctor
  6. 6

    Which overload is chosen when you pass null, and when are overloads resolved?

    medium

    Overloads are resolved at compile time from the static types of the arguments, not the runtime type. With print(Object) and print(String), a null argument picks print(String) because String is the most specific applicable type. If you add print(Integer) as well, the call becomes ambiguous and does not compile. Overriding, by contrast, is resolved at runtime from the actual object.

    java
    static void print(Object o) { System.out.println("Object"); }
    static void print(String s) { System.out.println("String"); }
    public static void main(String[] a) {
        print(null);              // String
        Object o = "hi";
        print(o);                 // Object: static type decides
    }
  7. 7

    What does this print: System.out.println('a' + 1) and the variants?

    easy

    Adding a char and an int is numeric addition after promotion to int, so it prints 98. Casting back with (char) gives b. If the left operand is a String, + becomes concatenation and evaluation goes left to right, so "" + 'a' + 1 gives a1 while 1 + 2 + "x" gives 3x.

    java
    System.out.println('a' + 1);          // 98
    System.out.println((char) ('a' + 1)); // b
    System.out.println("" + 'a' + 1);     // a1
    System.out.println(1 + 2 + "x");      // 3x
    System.out.println("x" + 1 + 2);      // x12
  8. 8

    What happens on int overflow? What is Math.abs(Integer.MIN_VALUE)?

    medium

    Java int arithmetic wraps around silently in two's complement. Integer.MAX_VALUE + 1 equals Integer.MIN_VALUE, which is -2147483648. Because the positive counterpart of MIN_VALUE does not fit in an int, Math.abs(Integer.MIN_VALUE) returns MIN_VALUE itself, a negative number. Use Math.addExact, multiplyExact or toIntExact to get an ArithmeticException instead, or switch to long or BigInteger.

    java
    System.out.println(Integer.MAX_VALUE + 1);     // -2147483648
    System.out.println(Math.abs(Integer.MIN_VALUE)); // -2147483648
    // Math.addExact(Integer.MAX_VALUE, 1) throws ArithmeticException
  9. 9

    Why does 0.1 + 0.2 not equal 0.3, and how do you compare doubles or handle money?

    medium

    Binary floating point cannot represent 0.1 or 0.2 exactly, so the sum is 0.30000000000000004. Compare with a tolerance, for example Math.abs(a - b) < 1e-9. For money use BigDecimal built from a String (new BigDecimal("0.10")), never from a double, or store integer paise. Also remember BigDecimal equals() compares scale, so 2.0 and 2.00 are not equal while compareTo returns 0.

    java
    System.out.println(0.1 + 0.2);                    // 0.30000000000000004
    System.out.println(0.1 + 0.2 == 0.3);              // false
    System.out.println(new BigDecimal("2.0").equals(new BigDecimal("2.00")));   // false
    System.out.println(new BigDecimal("2.0").compareTo(new BigDecimal("2.00"))); // 0
  10. 10

    Why does short s = 1; s = s + 1; fail to compile but s += 1 works?

    medium

    In s + 1 the operands are promoted to int, so the result is an int and cannot be assigned to a short without a cast. Compound assignment operators such as += include an implicit narrowing cast, so s += 1 compiles and behaves like s = (short)(s + 1). The same applies to byte and char.

  11. 11

    What is the difference between final, finally and finalize?

    easy

    final is a modifier: a final variable is assigned once, a final method cannot be overridden and a final class cannot be extended. finally is a block that runs after try and catch whether or not an exception occurred. finalize() was an Object method called by the garbage collector before reclaiming an object; it is deprecated for removal since Java 18 and should be replaced with try-with-resources or java.lang.ref.Cleaner.

  12. 12

    What happens when you unbox a null Integer? Predict the output.

    medium

    Unboxing calls intValue() on the object, so a null Integer throws NullPointerException. This hides in ternaries too: in cond ? 1 : nullInteger the type is int, so the null is unboxed when the condition is false.

    java
    Integer i = null;
    try {
        int j = i;                       // NullPointerException
    } catch (NullPointerException e) {
        System.out.println("NPE");
    }
    Map<String,Integer> m = new HashMap<>();
    // int n = m.get("x");              // also NPE
  13. 13

    Explain stack versus heap memory in Java.

    medium

    Each thread has its own stack that holds frames: local primitives and references, plus partial results. Objects and arrays live on the heap, which is shared and managed by the garbage collector. A reference variable lives in a frame while the object it points to lives on the heap. StackOverflowError means the call stack was exhausted, usually by unbounded recursion, whereas OutOfMemoryError means the heap (or metaspace) cannot satisfy an allocation. See JVM internals for the full memory model.

  14. 14

    Which access modifiers exist and what does package-private mean?

    easy

    public is visible everywhere, protected within the package and to subclasses, package-private (no keyword) only within the same package, and private only inside the declaring class. Top-level classes can only be public or package-private. With modules, a public type is also visible outside its module only if the package is exported.

  15. 15

    What are records and sealed classes (Java 17), and what do they replace?

    medium

    A record is a transparent, shallowly immutable data carrier: the compiler generates the constructor, accessors, equals, hashCode and toString from the components. A sealed class or interface lists its permitted subclasses, which lets the compiler check switch pattern matching for exhaustiveness. Together they model algebraic data types without the boilerplate of a hand-written value class.

    java
    sealed interface Shape permits Circle, Square {}
    record Circle(double r) implements Shape {}
    record Square(double side) implements Shape {}
    
    static double area(Shape s) {
        return switch (s) {
            case Circle c -> Math.PI * c.r() * c.r();
            case Square q -> q.side() * q.side();
        };   // no default needed: the hierarchy is sealed
    }
  16. 16

    Predict the output of a ternary that mixes char and int operands.

    hard

    If one operand is a char and the other is an int constant that fits in a char, the ternary type is char. So true ? 'b' : 0 prints b, not 98. If the int operand is a variable that is not a constant, binary numeric promotion makes the result int and it prints a number. This is a favourite trap because the same-looking expressions print different things.

    java
    int zero = 0;
    System.out.println(true ? 'b' : 0);    // b   (0 is a constant fitting in char)
    System.out.println(true ? 'b' : zero); // 98  (promoted to int)
  17. 17

    Can you override a static method? What happens with field hiding?

    hard

    Static methods are not overridden, they are hidden: the version called depends on the compile-time type of the reference. The same is true for fields, which have no polymorphism at all. Only instance methods dispatch on the runtime type.

    java
    class P { static String who() { return "P"; } String name = "P"; }
    class C extends P { static String who() { return "C"; } String name = "C"; }
    P p = new C();
    System.out.println(p.who());   // P
    System.out.println(p.name);    // P
    System.out.println(((C) p).name); // C

Frequently asked questions

How many Java questions should a fresher prepare?

Cover the sixteen on this page, then the OOP, collections, strings and exceptions pages. Depth on fifty questions beats shallow reading of two hundred, because follow-ups probe the reason behind each answer.

Which Java version do interviews assume?

Most expect Java 8 features (lambdas, streams) as a baseline and increasingly ask about Java 17 features such as records, sealed classes, text blocks and switch expressions.

Are output-prediction questions common in written tests?

Yes. Online assessments for service companies commonly include code snippets with a multiple-choice output, mostly on static, string, inheritance and exception behaviour.

Should I learn Spring before interviews?

For backend roles, yes, but core Java is checked first. See Spring Boot questions once the fundamentals are comfortable.

Related guides

More in Programming Language Interview Questions by Language

See all in this section