Firstly, you never set an object to null. That concept has no meaning. You can assign a value of null to a variable, but you need to distinguish between the concepts of "variable" and "object" very carefully. Once you do, your question will sort of answer itself :)

Now in terms of "shallow copy" vs "deep copy" - it's probably worth avoiding the term "shallow copy" here, as usually a shallow copy involves creating a new object, but just copying the fields of an existing object directly. A deep copy would take a copy of the objects referred to by those fields as well (for reference type fields). A simple assignment like this:

ArrayList<String> list1 = new ArrayList<String>();
ArrayList<String> list2 = list1;

... doesn't do either a shallow copy or a deep copy in that sense. It just copies the reference. After the code above, list1 and list2 are independent variables - they just happen to have the same values (references) at the moment. We could change the value of one of them, and it wouldn't affect the other:

list1 = null;
System.out.println(list2.size()); // Just prints 0

Now if instead of changing the variables, we make a change to the object that the variables' values refer to, that change will be visible via the other variable too:

list2.add("Foo");
System.out.println(list1.get(0)); // Prints Foo

So back to your original question - you never store actual objects in a map, list, array etc. You only ever store references. An object can only be garbage collected when there are no ways of "live" code reaching that object any more. So in this case:

List<String> list = new ArrayList<String>();
Map<String, List<String>> map = new HashMap<String, List<String>>();
map.put("Foo", list);
list = null;

... the ArrayList object still can't be garbage collected, because the Map has an entry which refers to it.

Answer from Jon Skeet on Stack Overflow
Top answer
1 of 7
59

Firstly, you never set an object to null. That concept has no meaning. You can assign a value of null to a variable, but you need to distinguish between the concepts of "variable" and "object" very carefully. Once you do, your question will sort of answer itself :)

Now in terms of "shallow copy" vs "deep copy" - it's probably worth avoiding the term "shallow copy" here, as usually a shallow copy involves creating a new object, but just copying the fields of an existing object directly. A deep copy would take a copy of the objects referred to by those fields as well (for reference type fields). A simple assignment like this:

ArrayList<String> list1 = new ArrayList<String>();
ArrayList<String> list2 = list1;

... doesn't do either a shallow copy or a deep copy in that sense. It just copies the reference. After the code above, list1 and list2 are independent variables - they just happen to have the same values (references) at the moment. We could change the value of one of them, and it wouldn't affect the other:

list1 = null;
System.out.println(list2.size()); // Just prints 0

Now if instead of changing the variables, we make a change to the object that the variables' values refer to, that change will be visible via the other variable too:

list2.add("Foo");
System.out.println(list1.get(0)); // Prints Foo

So back to your original question - you never store actual objects in a map, list, array etc. You only ever store references. An object can only be garbage collected when there are no ways of "live" code reaching that object any more. So in this case:

List<String> list = new ArrayList<String>();
Map<String, List<String>> map = new HashMap<String, List<String>>();
map.put("Foo", list);
list = null;

... the ArrayList object still can't be garbage collected, because the Map has an entry which refers to it.

2 of 7
10

To clear the variable

According to my knowledge,

If you are going to reuse the variable, then use

               Object.clear();

If you are not going to reuse, then define

               Object=null;

Note: Compare to removeAll(), clear() is faster.

Please correct me, If I am wrong....

🌐
Oracle
docs.oracle.com › cd › E19159-01 › 819-3681 › abebi › index.html
Assign null to Variables That Are No Longer Needed (Sun Java System Application Server 9.1 Performance Tuning Guide)
Explicitly assigning a null value to variables that are no longer needed helps the garbage collector to identify the parts of memory that can be safely reclaimed. Although Java provides memory management, it does not prevent memory leaks or using excessive amounts of memory. An application may induce memory leaks by not releasing object ...
Discussions

How to assign a "null" value to a single element in an int[] array in Java - Stack Overflow
Object value can be null but int primitive type can't be null. so to solve this issue yo have to make Integer[] num = new Integer[3]; ... In Java programming, null can be assigned to any variable of a reference type (that is, a non-primitive type) to indicate that the variable does not refer ... More on stackoverflow.com
🌐 stackoverflow.com
Java, What is the difference between assigning null to object and just declaration - Stack Overflow
As mentioned, object reference as instance variable need not be assigned null as those take null as default value. More on stackoverflow.com
🌐 stackoverflow.com
java - Assign an object to null - Stack Overflow
If I instantiate an object and pass it to an function, in this function I assign this object to null. It seems when return from the function, the object still there. I just want to know when I assign null, what happens. ... You can never assign to an object. All you ever have are primitives and references. A reference is either null or a pointer to an object of suitable class. Java arguments are passed by value... More on stackoverflow.com
🌐 stackoverflow.com
May 22, 2017
Why do you set your variables to null (JAVA)
This code is not even valid Java. int is a primitive data type and can never be null. It can be 0 (zero), but not null. null is reserved for object data types. More on reddit.com
🌐 r/learnprogramming
14
1
June 27, 2018
🌐
Coderanch
coderanch.com › t › 386100 › java › Setting-objects-null
Setting objects to null (Java in General forum at Coderanch)
August 28, 2008 - If the reference is local to a method then setting it to null just before the method returns will make no difference because as soon as the method returns, the reference goes out of scope and so is not considered to refer to the object anymore anyway. If the reference is an instance variable, then setting it to null makes the object available for GC as long as there are no other references to it.
🌐
Silicon Cloud
silicloud.com › home › java null assignment guide
Java Null Assignment Guide - Blog - Silicon Cloud
August 2, 2025 - In Java, you can assign a null value to an object using the assignment operator (=).
Find elsewhere
🌐
Net Informations
net-informations.com › java › cjava › objectonull.htm
How setting an Object to null help Garbage Collection?
Local variables naturally go out of scope when the method returns, and setting them to null is redundant since the variables cease to exist anyway. If there are no other references to the objects that the variables pointed to, those objects become eligible for garbage collection. The key factor in determining an object's reachability is whether it can participate in ongoing computations. If your code refers to a local variable, and there are no other references to it, assigning null to it might cause the object to be collected.
🌐
Logit
logit.io › blog › post › null-in-java
The Concept Of Null In Java
February 4, 2025 - To represent 'null' in Java bytecode, three distinct instructions are primarily utilized. aconst_null: This instruction is used to push a 'null' onto the stack. For example, when you initialize an object with null, like , is the instruction executed.
🌐
Upwork
upwork.com › resources › articles › null in java: understanding the basics
Null in Java: Understanding the Basics - Upwork
August 5, 2024 - By adopting these best practices, ... used to denote the absence of an object. It is strictly typed, meaning it can only be assigned to reference types....
🌐
Medium
donraab.medium.com › what-if-null-was-an-object-in-java-3f1974954be2
What if null was an Object in Java? - Donald Raab - Medium
January 5, 2024 - In Java, there is a literal named null. You can assign null to any variable that has an Object type, but the reference the variable points to is not an instance of an Object.
🌐
DEV Community
dev.to › dj_devjournal › understanding-null-in-java-4o31
Understanding null in Java - DEV Community
October 16, 2019 - null is not an Object or neither a type. It’s just a special value, which can be assigned to any reference type.
🌐
DataCamp
datacamp.com › doc › java › null
null Keyword in Java: Usage & Examples
Null Checks: Always perform null checks before calling methods on objects to avoid NullPointerException. ... Default Initialization: Be aware that reference type instance variables are automatically initialized to null if not explicitly initialized. Optional Class: Consider using the Optional class introduced in Java 8 to handle nullable values more gracefully.
Top answer
1 of 7
16

No, because a is a reference (not an object as in this question's title) and no method can modify the value of a reference except the method in which it is defined (I assume from the code context that a is a local variable).

Since Java doesn't have pass-by-reference, what you ask cannot be done: there's no way to collect addresses-of references in order to manage the addresses pointed to. You might use a wrapper object, but not sure what'd be the point.

2 of 7
5

As everyone else has said, this simply isn't possible. If it's cleaning up resources you're after, then you might consider using a pattern such as:

class A {

    private boolean cleanedUp;

    public void cleanUp() {
        // clean up any resources
        cleanedUp = true;
    }

    public boolean isCleanedUp() {
        return cleanedUp;
    }
}

And then using it like so:

A a = new A();
a.cleanUp();
if (a.isCleanedUp()) {
    ...
}

A better solution might be to implement the java.io.Closeable or java.lang.AutoCloseable interfaces depending on your circumstance:

class B implements AutoCloseable {

    private boolean closed;

    public boolean isClosed() {
        return closed;
    }

    @Override public void close() throws Exception {
        // clean up any resources
        closed = true;
    }
}

In which case you can use a try-with-resources statement:

try (B b = new B()) {
    // do stuff
} catch (Exception ex) {
    // oh crap...
}

Or you could even combine the two and do it that way, whichever you prefer.

Or lastly you could do it the way William Morrison explained (though I'd probably cheat and just use java.util.concurrent.atomic.AtomicReference instead of making my own class, and it comes with the added benefit of being a generified type), which, depending on your circumstance, may really be unnecessary. After all, you could always just do (even though it might seem a little odd):

A a = new A();

a.doStuffAndDisappear();
a = null;

if(a == null){
     //...
}
🌐
Refactoring.Guru
refactoring.guru › home › techniques › simplifying conditional expressions
Introduce Null Object
January 1, 2026 - Instead of null, return a null object that exhibits the default behavior. ... class NullCustomer extends Customer { boolean isNull() { return true; } Plan getPlan() { return new NullPlan(); } // Some other NULL functionality.
🌐
W3Docs
w3docs.com › java
Can an int be null in Java? | W3Docs
If you want to store a null value in a variable in Java, you can use a wrapper class such as Integer. The Integer class is an object that wraps an int value, and it can be assigned the value null.
🌐
GeeksforGeeks
geeksforgeeks.org › java › interesting-facts-about-null-in-java
Interesting facts about null in Java - GeeksforGeeks
September 3, 2024 - 3. Type of null: Unlike the common misconception, null is not Object or neither a type. It's just a special value, which can be assigned to any reference type and you can type cast null to any type Examples: