Click here to Skip to main content
15,887,596 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
class Cardboard{
	Short story = 200;
	Cardboard go(Cardboard cb){
		cb = null;
		return cb;
	}
	public static void main(String args[]){
		Cardboard c1 = new Cardboard();
		Cardboard c2 = new Cardboard();
		Cardboard c3 = c1.go(c2);
		c1 = null;
	}
}


What I have tried:

According to me all 3 objects c1,c2,c3 must be available for garbage collection as c2 is set to null in go() and it's reference is passed to c3 thus, both refer to null and in the end c1 is also made to refer to null.
Posted
Updated 1-Nov-17 23:53pm
v2

After the main() code is run all objects are available for garbage collection.

Garbage collections occur when the JVM hits memory limits, not necessarily immediately after a method completes.

Setting an variable to null may not put that object up for garbage collection, garbage collection checks for "actively referenced" objects throughout the memory.
 
Share this answer
 
Comments
Member 13409417 2-Nov-17 5:48am    
I am asking here which CAN be available for garbage collection
Uhm....
Try:
Java
  Short story = 200;
  Cardboard go(Cardboard cb){
    cb = null;
    return cb;
  }
  public static void main(String args[]){
    Cardboard c1 = new Cardboard();
    Cardboard c2 = new Cardboard();
    Cardboard c3 = c1.go(c2);
    c1 = null;
    System.out.println(c2.story);
  }
}

Hint: Java parameters are always passed by value.
 
Share this answer
 
Comments
Member 13409417 2-Nov-17 5:53am    
Please elaborate your solution,
CPallini 2-Nov-17 6:46am    
The method go doesn't change c2, because the latter is passed by value.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900