JVM & Memory Basics Questions with Answers

23 practice questions on JVM & Memory Basics (Core Java) with answers and step-by-step solutions. Try 10 samples below, then practise all 23 free in the AptiNest app.

Sample questions

Question 1Easy

Which component verifies and executes .class files, making Java bytecode portable across operating systems?

  1. The javac compiler
  2. The Java Virtual Machine (JVM)
  3. The JDK documentation tool javadoc
  4. The operating system kernel directly

Answer: B. The Java Virtual Machine (JVM)

Explanation

javac compiles source to platform-neutral bytecode; each platform's JVM loads, verifies and runs that bytecode ("write once, run anywhere").

Step-by-step solution

  1. Javac compiles source code into platform-neutral bytecode in .class files.
  2. The JVM loads, verifies and runs that bytecode on each operating system.
  3. This is why Java programs are portable; the answer is option B.

Why the other options are wrong

  • A. Javac only compiles source code; it does not run .class files.
  • C. Javadoc generates documentation and does not run bytecode.
  • D. The operating system does not read bytecode directly; the JVM sits between them.

Tip: Source to bytecode is javac; bytecode to running program is the JVM.

Question 2Easy

When does an object become eligible for garbage collection?

  1. When System.gc() is called on it
  2. When its reference count reaches exactly zero and finalize() has run
  3. When it is no longer reachable from any live thread or static reference
  4. As soon as the method that created it returns

Answer: C. When it is no longer reachable from any live thread or static reference

Explanation

Java GC is based on reachability from GC roots, not reference counting; unreachable objects (even cycles) are eligible, but collection time is not guaranteed.

Step-by-step solution

  1. An object becomes eligible when no live thread can reach it.
  2. Static references and local variables are GC roots.
  3. If an object is unreachable from all GC roots, it's marked for collection.
  4. Reference counting is not used in Java for GC eligibility.
  5. Finalize() runs before collection but doesn't guarantee collection.
  6. Correct answer: When it is no longer reachable from any live thread or static reference.

Why the other options are wrong

  • A. System.gc() is only a request; eligibility depends on reachability, not on calling gc.
  • B. Java GC does not use reference counting, and finalize() is not required for eligibility.
  • D. Only unreachability matters; a returned object may still be referenced elsewhere, so it stays alive.

Tip: Remember: GC eligibility depends on reachability, not reference count.

Question 3Easy

Which JVM option sets the maximum heap size?

  1. -Xmx
  2. -Xss
  3. -Xms
  4. -XX:MaxMetaspaceSize

Answer: A. -Xmx

Explanation

-Xmx sets the maximum heap, -Xms the initial heap, -Xss the per-thread stack size, and MaxMetaspaceSize caps class metadata.

Step-by-step solution

  1. -Xmx sets the maximum heap size.
  2. -Xms sets the initial heap size, and -Xss sets the stack size of each thread.
  3. -XX:MaxMetaspaceSize caps class metadata.
  4. The answer is option A, -Xmx.

Why the other options are wrong

  • B. -Xss sets the per-thread stack size, not the heap size.
  • C. -Xms sets the initial heap size, not the maximum.
  • D. MaxMetaspaceSize caps class metadata, not the heap.

Tip: Remember: Xmx is max heap, Xms is start heap, Xss is thread stack.

Question 4Easy

What is the output?

public class Main {
    static int depth(int n) {
        try {
            return depth(n + 1);
        } catch (StackOverflowError e) {
            return -1;
        }
    }

    public static void main(String[] args) {
        System.out.println(depth(0));
    }
}
  1. -1
  2. The program never terminates
  3. 0
  4. OutOfMemoryError

Answer: A. -1

Explanation

Unbounded recursion exhausts the thread stack and throws StackOverflowError; it is caught at the deepest frame, which returns -1, and every caller passes that up.

Step-by-step solution

  1. depth(0) calls depth(1), which calls depth(2), etc., infinitely.
  2. Each call adds a frame to the stack until it overflows.
  3. StackOverflowError is thrown at the deepest call, which returns -1.
  4. The return value -1 propagates up through all caller frames.
  5. Finally, main() prints -1 as the output.

Why the other options are wrong

  • B. The StackOverflowError is caught in each frame, so the recursion unwinds and the program ends.
  • C. The deepest catch returns -1, and that value propagates up, so the output is -1.
  • D. The error is a StackOverflowError caught in code, not an OutOfMemoryError from heap exhaustion.

Tip: Unbounded recursion causes StackOverflowError, caught and returned as -1.

Question 5Medium

Since Java 7 (HotSpot), where is the String constant pool (interned strings) stored?

  1. In the main heap
  2. In the PermGen space
  3. On each thread's stack
  4. In the metaspace together with class metadata

Answer: A. In the main heap

Explanation

The string pool moved from PermGen to the regular heap in Java 7, so interned strings can be garbage-collected like other objects.

Step-by-step solution

  1. Since Java 7 (HotSpot), the string constant pool is stored in the regular heap.
  2. Because it is on the heap, interned strings can be garbage collected like other objects.
  3. The answer is option A, the main heap.

Why the other options are wrong

  • B. PermGen held the string pool in older Java versions, not since Java 7.
  • C. Thread stacks hold local variables and references, not the string pool.
  • D. Metaspace holds class metadata, not interned strings.

Tip: The string pool is part of the heap in modern HotSpot; class metadata is a separate area.

Question 6Medium

What is the main purpose of bytecode verification when a class is loaded?

  1. To compile the bytecode to native code
  2. To initialise static fields to their declared values
  3. To check the source code for syntax errors
  4. To check that the bytecode is type-safe and cannot corrupt the JVM, e.g. no stack overflow of operands or illegal casts

Answer: D. To check that the bytecode is type-safe and cannot corrupt the JVM, e.g. no stack overflow of operands or illegal casts

Explanation

Linking includes verification, which rejects malformed or unsafe bytecode before it runs; static initialisers run later, during initialisation.

Step-by-step solution

  1. Bytecode verification ensures the code is safe for JVM execution.
  2. It checks for type safety and prevents illegal operations.
  3. Verification stops unsafe bytecode from running on JVM.
  4. It avoids issues like stack overflow or invalid casts.
  5. Final answer: To check that the bytecode is type-safe and cannot corrupt the JVM, e.g. no stack overflow of operands or illegal casts.

Why the other options are wrong

  • A. Compiling to native code is the JIT's job, not verification, which only checks bytecode safety.
  • B. Setting static fields to declared values is class initialisation, not verification.
  • C. Verification works on bytecode, not source code; syntax errors are caught by the compiler earlier.

Tip: Verify bytecode to prevent JVM corruption and runtime errors.

Question 7Medium

Two objects refer only to each other and nothing else refers to either of them. What happens?

  1. Neither can ever be collected because each has a reference
  2. Only the object created first is eligible
  3. The JVM throws a memory leak exception
  4. Both are eligible for garbage collection

Answer: D. Both are eligible for garbage collection

Explanation

The JVM collects objects unreachable from GC roots; a cycle that is cut off from the roots is garbage, unlike in pure reference-counting schemes.

Step-by-step solution

  1. Each object has a reference to the other, forming a cycle.
  2. The cycle is not connected to any GC root.
  3. JVM can collect objects unreachable from roots.
  4. Cycle is considered garbage as it has no live references.
  5. Both objects are eligible for garbage collection.

Why the other options are wrong

  • A. A cycle of references does not keep objects alive; unreachable cycles from GC roots are still collected.
  • B. Only reachability from GC roots matters; creation order makes no difference, and both objects are unreachable.
  • C. The JVM does not throw a memory leak exception for cycles; the garbage collector simply reclaims them.

Tip: Cycles not connected to GC roots are eligible for garbage collection.

Question 8Medium

Why is overriding finalize() discouraged in modern Java?

  1. It runs immediately when a reference is set to null, which is too early
  2. It is called on every method return and slows the program
  3. It prevents an object from ever being collected
  4. It is deprecated: it may run late or never and adds GC overhead; use try-with-resources or Cleaner instead

Answer: D. It is deprecated: it may run late or never and adds GC overhead; use try-with-resources or Cleaner instead

Explanation

finalize() has been deprecated (for removal) since Java 9/18: there is no guarantee when or whether it runs, so resources should be released explicitly.

Step-by-step solution

  1. finalize() is deprecated and may run late or never.
  2. It adds overhead to garbage collection process.
  3. Uncertain execution time makes resource management unreliable.
  4. Modern Java recommends explicit resource release instead.
  5. Use try-with-resources or Cleaner for deterministic cleanup.
  6. Finalize() should be avoided for predictable behavior.

Why the other options are wrong

  • A. finalize() does not run when a reference is set to null; it runs later, if at all, during GC.
  • B. finalize() is called only on objects being collected, not on every method return, so that is not why.
  • C. finalize() does not stop collection; an object with finalize() is still collected, just later.

Tip: Avoid finalize(), use try-with-resources for clean resource handling.

Question 9Hard

What is the output?

class Lazy {
    static final String X = "const";
    static { System.out.println("init"); }
}

public class Main {
    public static void main(String[] args) {
        System.out.print("main ");
        System.out.println(Lazy.X);
    }
}
  1. init main const
  2. main const
  3. main const init
  4. main init const

Answer: B. main const

Explanation

Lazy.X is a compile-time constant, so javac inlines "const" into Main and the Lazy class is never initialised; its static block never runs.

Step-by-step solution

  1. Lazy.X is a static final String with a constant value, so javac inlines "const" into Main.
  2. Reading Lazy.X does not touch the Lazy class, so Lazy is never initialised and its static block never runs.
  3. Output: main const, which is option B.

Why the other options are wrong

  • A. Init is never printed, because Lazy is never initialised.
  • C. The order is wrong, and init is never printed.
  • D. The order is wrong, and init is never printed.

Tip: A static final constant of a primitive or String type with a constant value is inlined, so it does not trigger class loading.

Question 10Hard

Which of the following is a GC root (a starting point for reachability)?

  1. A local variable in an active method frame of a running thread
  2. An object referenced only by another unreachable object
  3. Every object created in the last minor GC cycle
  4. Any object whose finalize() has not run yet

Answer: A. A local variable in an active method frame of a running thread

Explanation

GC roots include locals and parameters on live thread stacks, static fields of loaded classes and JNI references; anything reachable from them stays alive.

Step-by-step solution

  1. Local variables in active methods are GC roots.
  2. They are part of running thread stacks.
  3. Reachable objects from these roots stay alive.
  4. Unreachable objects do not start reachability chains.
  5. Objects created in last minor GC cycle may be collected.
  6. Finalize() not run does not make object a root.

Why the other options are wrong

  • B. An object referenced only by an unreachable object is not a root; it is reachable only through garbage.
  • C. Objects from the last minor GC are not roots; they are kept or collected based on reachability from roots.
  • D. A pending finalize() does not make an object a root; it is not a reason for the object to stay alive.

Tip: Remember: local variables in active methods are always GC roots.

Practise all 23 questions free

The full question bank with timed practice, progress tracking and Vidya, your AI tutor. Free, no ads.

Open this topic in the app →

Related topics

See all Core Java topics · All topics