Memory management & garbage collection (concept)

Computer Science · Java

Question 1 of 10

0

    In C, memory obtained with malloc must be released with:

    Stuck? Read the explanation

    Unlocks at a streak of 5 correct answers in a row.

    Print a free worksheet (PDF)

    Embed this practice on your site or class page

    Paste this HTML into your page. Students practise right there; it is free and needs no account.

    Memory management & garbage collection (concept) explained

    Java manages memory automatically. You create objects with new, and the garbage collector frees the memory of objects that the program can no longer reach. Programmers do not free memory by hand.

    Objects live on the heap, and method calls and local variables live on the stack. A variable holding a reference keeps its object reachable. When no chain of references from the running program leads to an object, the object becomes eligible for garbage collection. Setting a variable to null removes one reference, and the object is collected only if nothing else refers to it. The JVM decides when collection happens, so you cannot rely on it running at a particular moment, and System.gc() is only a request. Java can still leak memory when unwanted objects stay reachable, such as entries that a long-lived list keeps adding.

    List<byte[]> cache = new ArrayList<>();
    for (int i = 0; i < 3; i++) {
        cache.add(new byte[1_000_000]);
    }
    cache.clear();
    

    Worked example

    Trace the code above.

    1. Each new byte[1_000_000] allocates 1,000,000 bytes, which is 1 MB, so the loop allocates 3 MB in total. The arrays stay reachable through cache.
    2. cache.clear() removes the three references from the list.
    3. Nothing else refers to the arrays, so they become eligible for collection. The collector reclaims them when it next runs.
    4. If cache were a field that never got cleared, the arrays would stay reachable and memory use would keep growing.

    What you will practise

    101 multiple-choice questions (Easy, Medium, Hard). Each answer is followed by an explanation.

    Example questions

    • Java manages memory via:
    • Garbage collection removes:
    • An object becomes garbage when:
    • The heap holds:
    • A memory leak in Java means:
    • Local variables of primitive type inside a Java method are stored on the:
    • The new keyword in Java:
    • Java has no keyword to free an object manually. Which statement is correct?

    …and 93 more.