Want to protect your cyber security and still get fast solutions? Ask a secure question today.Go Premium

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 607
  • Last Modified:

How many objects are eligible for garbage collection?

I am studying for a Java Certification Exam. I approached this problem in a book written by "Sierra-Bates", where I need to solve multiple choice question. When the //do stuff is reached, how many objects are eligible for GC?

The code is given below, and I also use print statement inside the constructor to count the number of Objects created.

Obviously, to me it looks like 2 Objects are created, and 1 Object is eligible for Garbage Collection, since c1 (instance variable) is pointed to null.
However, the answer (given in the book) is 2 Objects are eligible for Garbage Collection. The explanation written is, "Only one CardBoard object (c1) is eligible, but it has an associated Short wrapper object that is also eligible"

My Question is, why the "Short story" variable is counted as an Object, and eligible for Garbage Collection?  


class CardBoard
{
	Short story = 200;
	CardBoard()
	{
		System.out.println("CardBoard Object: " + toString());
	}
			
	public static void main (String [] args)
	{
		CardBoard c1 = new CardBoard();
		CardBoard c2 = new CardBoard();
		c1 = null;
                //do stuff
	}
}

Open in new window


I would appreciate if you could explain the "explanation" given in the book :)
0
techbro
Asked:
techbro
2 Solutions
 
objectsCommented:
>       Short story = 200;

Because it is using the Short wrapper class (not a short primitive)
That line is the same as saying


      Short story = new Short(200);
0
 
prerakshethCommented:
short is a basic data type, while Short is a wrapper type.
Beginning Java 1.4, the basic data type to wrapper and vice versa is provided automatically (before that, it had to be done by hand) but it still creates an object for that.
0
 
techbroAuthor Commented:
Thank you for your time!
0

Featured Post

Get your problem seen by more experts

Be seen. Boost your question’s priority for more expert views and faster solutions

Tackle projects and never again get stuck behind a technical roadblock.
Join Now