ProAnswers.org

Garbage Collection in Java

What does garbage collection mean? Why is this term used in Java?

Consider the given block of statements




	
		 
	
		
			
				
					
						1
					
						2
					
						3
					
						4
					
						5
				
				
					
						
							{
						
							    String s = new String("abc");
						
							    //do something with s
						
							}
						
							//end of scope
					
				
			
		
	



Here, “s” is a reference to the string object with value “abc”.
We can use s to refer to the object within the given block(within curly braces).
“s” becomes out of scope when the block ends.



So, outside the block, the object is no longer referenced as the only reference it had is out of scope.



Java garbage collector keeps looking for such objects which have been created by “new” and are no longer referenced. It releases the memory for those objects.