Originally posted by padmini Babu:
How many objects are created by the following code?
1. StringBuffer s1 = new StringBuffer("abc");
2. StringBuffer s2 = s1;
3. StringBuffer s3 = new StringBuffer("abc");
Ans: 3
My problem:
How 3 . Only 2 objects are created by way of new . So i think the answer shd be two.
Raising Flares debut album 'Ignition' out now
http://www.raisingflares.com
Terry Doyle <br />SCPJ 1.4 , SCWCD , SCMAD(Beta)
Jane Griscti
SCJP, Co-author Mike Meyers' Java 2 Certification Passport
Originally posted by Jane Griscti:
Terence, Anand had it right. 's1', 's2' and 's3' are reference variables, not objects. Reference variables are always the same size and hold 'memory addresses'. The type, in this case StringBuffer, just defines the type of the object they will reference.
The code creates two StringBuffer objects ('new' always causes the creation of a new object).
Oops ... just saw the catch"abc" is a String literal, so, the first <code>new StringBuffer("abc")</code> actually creates a String literal object to hold the contents of "abc" and a StringBuffer object. The second <code>new StringBuffer("abc")</code> only creates the StringBuffer object. "abc" already exists as a String literal so a new one won't be created.
Total objects: 2 StringBuffer objects, 1 String literal.
Hope that helps.
All string literals in Java programs, such as "abc", are implemented as instances of this class.
Literal strings within the same class (�8) in the same package (�7) represent references to the same String object (�4.3.1).
Dave
Dave
Originally posted by padmini Babu:
Well Dave , alika, jane,
If according to you i assume that 3 objects are being created.
What cannot String s = "abc" - never be GCed?( I am speaking in the general context of string literals- they can never be GCEd even if set to null.)
If it is an object , it should be eligible for GC right??( Please note that the subject of GC is from the general point of view)
Please Scott, Cindy , Jane , please give a final answer. I am having my exams in a week's time.
Thanks padmini
Originally posted by Devavrat Bagayat:
Hello Ranchers,
I totally agree with Jane. I think, the explanation given is absolutely right.
"JavaRanch, where the deer and the Certified play" - David O'Meara
Jane Griscti
SCJP, Co-author Mike Meyers' Java 2 Certification Passport
"JavaRanch, where the deer and the Certified play" - David O'Meara
Originally posted by padmini Babu:
How many objects are created by the following code?
1. StringBuffer s1 = new StringBuffer("abc");
2. StringBuffer s2 = s1;
3. StringBuffer s3 = new StringBuffer("abc");
Ans: 3
My problem:
How 3 . Only 2 objects are created by way of new . So i think the answer shd be two.
So I left, I came home, and I ate some pie. And then I read this tiny ad:
New web page for Paul's Rocket Mass Heaters movies
https://coderanch.com/t/785239/web-page-Paul-Rocket-Mass
|