Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Java

References, copies, and memory in Java

References, copies, and memory in Java: In Java a reference variable denotes an object, so assignment or argument passing copies the reference rather than copying the object itself.

Version: Java SE 21 (JLS and Java SE API); examples verified on the repository Java runtime

Syntax

memory

In Java a reference variable denotes an object, so assignment or argument passing copies the reference rather than copying the object itself.

Create ownership boundaries with defensive copies such as List.copyOf and Arrays.copyOf, and expose immutable values or views.

final prevents changing the reference but not mutating the referenced object; array cloning and list copying are shallow, so nested elements may remain shared.

An unreachable object may be reclaimed by GC with no timing guarantee; close external resources with try-with-resources instead of relying on finalization.

The alias changes the shared array to original=[9, 2], Arrays.copyOf preserves copy=[1, 2], and shallow List.copyOf shows shared-element=AB plus outer-unmodifiable=true.

Examples

import java.util.Arrays;
import java.util.List;

public class Main {
    public static void main(String[] args) {
        int[] original = {1, 2};
        int[] alias = original;
        int[] copy = Arrays.copyOf(original, original.length);
        alias[0] = 9;
        System.out.println("original=" + Arrays.toString(original));
        System.out.println("copy=" + Arrays.toString(copy));

        var element = new StringBuilder("A");
        var shallow = List.copyOf(List.of(element));
        element.append("B");
        System.out.println("shared-element=" + shallow.get(0));
        try {
            shallow.add(new StringBuilder("C"));
        } catch (UnsupportedOperationException expected) {
            System.out.println("outer-unmodifiable=true");
        }
    }
}

Result

original=[9, 2]
copy=[1, 2]
shared-element=AB
outer-unmodifiable=true

The alias changes the shared array to original=[9, 2], Arrays.copyOf preserves copy=[1, 2], and shallow List.copyOf shows shared-element=AB plus outer-unmodifiable=true.

Sources