File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Same old garbage collection problem!!! Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Same old garbage collection problem!!!" Watch "Same old garbage collection problem!!!" New topic

Same old garbage collection problem!!!

Geeta Gune

Joined: Mar 19, 2002
Posts: 17

In the above code how many objects will be created? And how many shall be ready for garbage collection?
Also,i want to know 2 things:
1) Will it make a difference if i initialize the String s variable in the loop?
2) Will it make a difference if instead of the string i define an int?
I am very confused with these basic stuff.
Pls help.
Valentin Crettaz
Gold Digger

Joined: Aug 26, 2001
Posts: 7610
Basically, String literals are not garbage collected.
The String referred to by s is created once before the loop. No other object is created after that.
Please refer to the following discussions which handle the same topic:
[ November 29, 2002: Message edited by: Valentin Crettaz ]

[Blog] [Blogroll] [My Reviews] My Linked In
Alfred Kemety
Ranch Hand

Joined: Aug 14, 2002
Posts: 279
The code you wrote will have one String object created. IF this code was part of a method, and the method does NOT reference this object to a member variable, then supposedly there is one object elligibel for GC. BUT since this object is a string literal, the GC system doesn't garbage collected for optimization purposes.
If you make the initialization in the loop then there should be more object created with every loop but AGAIN since this is a String literal object, there will NOT be any new objects created because of the compiler optimization. UNLESS you use the new operator, there will not be new objects created during the loop itirations.
You can NOT garbage collect a primitive, GC system only works on objects.
but if you meant to creat an Object other than a String, like Integer object then yes it makes a difference since this time to initialize will use the new operator and will creat an object with each itiration - that's if the initialization is inside the loop -.
String s = "String"; //creats one String object
String s = new String("String"); // creats two String objects

Alfred Raouf - Egypt - SCJP 1.4<br />Kemety.equals(Egyptian) // returns true
I agree. Here's the link:
subject: Same old garbage collection problem!!!
It's not a secret anymore!