Granny's Programming Pearls
"inside of every large program is a small program struggling to get out"
JavaRanch.com/granny.jsp
Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Cloud/Virtualization forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

How many String objects ... ?!

 
Stefan Wendler
Greenhorn
Posts: 17
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi there I've found a very strange question in the SCJP 1.4 Book by K&B

------------------------------------
Given the following:

String x = new String("xyz");
y="abc";
x=x+y;

How Many Strings have been created:
A - 2
B - 3
C - 4
D - 5
--------------------------------------

I hava a big problem with this line -> y="abc" <- because this line wont compile as far as I know. Is this an errata or do I miss something?

Stefan
 
Barry Gaunt
Ranch Hand
Posts: 7729
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Yes, it should be String y = ...
 
Mani vannan
Ranch Hand
Posts: 185
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
5 objects.
 
A Kumar
Ranch Hand
Posts: 980
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi..

5 objects.

--------------------

Regards,
Mani Vannan




Line 1 - 2 objects...one each in heap and string literal pool
Line 2 - 1 object in pool
Line 3 - 2 objects one in heap and another in literal pool

Now x is a new string object with content "xyzabc"

Correct me if i am wrong..?

 
Mahendar Reddy
Ranch Hand
Posts: 73
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hello friends,
I hope ans is 3 but not 5.

String x = new String("xyz");
String y="abc";
x=x+y;

--------------------------------------------------------------------------------



Line 1 - 1 object...in heap
Line 2 - 1 object in heap and reference is stored in StringLiteralPool
Line 3 - 1 object in heap.
[ November 06, 2005: Message edited by: Mahendar Chada ]
 
Rob Spoor
Sheriff
Pie
Posts: 20495
54
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Mahendar Chada:
hello friends,
I hope ans is 3 but not 5.

String x = new String("xyz");
String y="abc";
x=x+y;

--------------------------------------------------------------------------------



Line 1 - 1 object...in heap
Line 2 - 1 object in StringPool(special type of memory)
Line 3 - 1 object in heap.
Line 1 creates two: String constant "xyz" in the StringPool and the newly created String in the heap. I agree with the other lines, so I think the answer should be 4.
 
Mahendar Reddy
Ranch Hand
Posts: 73
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Rob,
I have modified my prev post.
Please go through it once....
I hope the ans is 3 only...
 
Mandy Hou
Greenhorn
Posts: 21
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
four
L1 two
L2 one
L3 one
 
A Enter
Greenhorn
Posts: 20
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I agree four objects.
line 1:two x and new String("abc");
line 2 ne "abc" and y a same Object.but before y should have "String".
line 3 ne x + y has a new Object
 
Jay Pawar
Ranch Hand
Posts: 411
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
4 objects
1 on heap and 3 in the string constant pool.
 
Purujit Saha
Ranch Hand
Posts: 86
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The ans is 3 object....

I think Mahendar Chada is right
[ November 06, 2005: Message edited by: Purujit Saha ]
 
Mihai Lihatchi
Ranch Hand
Posts: 138
Java Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I believe there are 4 objects.
String x=new String("abc") actually generates 2 objects
1) a String object "abc" and
2) a new String object generated by the constructor of String ..
new String (String string) I believe.
Hence the following lines add another 2 objects.
4 is my answer and correct me if I am wrong,
 
Mahendar Reddy
Ranch Hand
Posts: 73
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi friends, ur interest on this question is praisable.

Please check this :

String x = new String("xyz");//1
String y = "xyz";
System.out.print(x==y);//3

--> As most of our friends said..at line#1 if an obj is created in
StringPool line#3 would have produce 'true' as o/p, but unfortunately it
is 'false'.So at line#1 only one object is created on the heap.

Friends as i know objects are never created in StringPool..
Only references to the objects are stored in the StringPool.

If I am wrong please correct me with evidence..Thanx in advance..

 
Purujit Saha
Ranch Hand
Posts: 86
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Whenever we create a String object..that is created in heap.
Now if the object is created as a String Literal(Not using a String Constructor),then only a reference of the Object that is created in heap is stored in the StringPool.

Take this Example.

class A
{
....
A a1=new A();
A a2=a1;
A a3=a2;

}
Here Only one object is created in the heap, and a1,a2,a3 only are the references of that Object.
Since the question is for Objects not References, so 3 objects are created in the heap.
So Mahendar is right.
[ November 07, 2005: Message edited by: Purujit Saha ]
 
Mihai Lihatchi
Ranch Hand
Posts: 138
Java Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
This applies to objects but Strings are immutable (that is they are created in a different manner and although not referenced stii remain in memory)
 
Purujit Saha
Ranch Hand
Posts: 86
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Friends Plz Refer to this Document
http://www.javaranch.com/journal/200409/Journal200409.jsp#a1
 
gangqiang zhang
Greenhorn
Posts: 5
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
3

L1--> 1 object("abc") on heap.
L2--> 1 Immutable String Object("xyz") in String Pool.
L3--> 1 Immutable String Object("abcxyz") in String Pool.

Regards
[ November 07, 2005: Message edited by: gangqiang zhang ]
 
sailaja vengala
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi all,

String x = new String("xyz");
// one reference variable, one string object"xyz"

String y ="abc";//one ref. variable one string object "abc"

x= x+y;// one reference variable, one string object. Here the referces r used to concatenate the string objects. for example say a literal is used , x=y + "efg" then "efg" is one string object(lost) and "abcefg" is another string object(now "xyz" object will be lost). so total of 2 objects will be created. since here the refereces r used which are x and y. only one string object will be created.

Please refer to kathey siera, java2 programmer certification book ,page354 second para and page 359 for an example to get my point.

so total of 3objects will be created.

Please correct me if i were wrong in any aspect.

Thank you
 
Steve Morrow
Ranch Hand
Posts: 657
Clojure Spring VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
String x = new String("xyz");
// one reference variable, one string object"xyz"

Not quite. There will be two different String objects after this line. One is created on the heap when the class is loaded, and is based on the literal "xyz". A second String object is created on the heap with the 'new' keyword, and has the same character sequence as the other String object. The two objects are not the same (e.g., x != "xyz").
 
Mahendar Reddy
Ranch Hand
Posts: 73
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Steve,
I don't know from where u got this concept.
But u r contraducting with my statement.
Could you make me agree with ur statement.Provide some material proving
ur stmt...

Adv thanx if u do so...
 
Jyothi Bhogadi
Ranch Hand
Posts: 47
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hi mahender ,
i think you will have to agree with what steve is trying to explain.....
As you have said ... to make u agree with steve's statement..... check out this thread

regards
jyothi.
 
A Kumar
Ranch Hand
Posts: 980
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi..

Whats the final figure..?

3 / 4 / 5 ..

I would go for 4...
 
Purujit Saha
Ranch Hand
Posts: 86
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hi jyoti...plz give some Documents not referencs of somebody's comment..
we can't believe on somebody's comments...
 
Purujit Saha
Ranch Hand
Posts: 86
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Again request you friends...to read this article...
http://www.javaranch.com/journal/200409/Journal200409.jsp#a1
 
harish shankarnarayan
Ranch Hand
Posts: 158
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
wats the final answer???

line 1: two obj
line 2: one obj
line 3: one obj

total four objects according to me
 
Steve Morrow
Ranch Hand
Posts: 657
Clojure Spring VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I don't know from where u got this concept.

The concept is how the language is defined to work, and can be found in the The Java Language Specification and the Virtual Machine Specification. This topic gets discussed a bunch around here, so rather than repeat it, I'll just cite some quick references:

http://java.sun.com/docs/books/vmspec/2nd-edition/html/Overview.doc.html#22972
http://java.sun.com/docs/books/vmspec/2nd-edition/html/ConstantPool.doc.html#67960
http://java.sun.com/docs/books/vmspec/2nd-edition/html/ClassFile.doc.html#20080

http://java.sun.com/docs/books/jls/third_edition/html/lexical.html#248733

String literals

Good luck!
 
Steve Morrow
Ranch Hand
Posts: 657
Clojure Spring VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by harish shankarnarayan:
total four objects according to me

Four is correct (two literals, one created from the 'new' keyword, and one created from the concatenation).
 
Purujit Saha
Ranch Hand
Posts: 86
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Can anyone of you Focus in this area .....
Corey McGlone,Marcus Green, Barry Gaunt, Jason Menard, Dirk

Please...
 
Purujit Saha
Ranch Hand
Posts: 86
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello,
Corey McGlone,Marcus Green, Barry Gaunt, Jason Menard, Dirk

Can anyone of you Express your view on this topic..

Please.
 
Steve Morrow
Ranch Hand
Posts: 657
Clojure Spring VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Corey McGlone,Marcus Green, Barry Gaunt, Jason Menard, Dirk


Apparently, I haven't reached "trustworthy" status yet...
 
Steve Morrow
Ranch Hand
Posts: 657
Clojure Spring VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator


While I don't carry as much weight around here as the "big boys", I'll offer a more detailed explanation as to what is actually going on with this code. We'll take a look at the Java 1.5 bytecodes in order to grasp what's happening behind the scenes. Stick with me...

The above code is compiled to the following bytecodes (as displayed with the "javap -c" command):



Let's take a closer look at what this code does...

This creates a new String object on the heap, but the object is uninitialized as of yet. A reference to this object is pushed onto the stack. For purposes of illustration, I'll say this reference value is 0x01. Don't attribute any special meaning to this; it just represents a pointer to an object on the heap.
Stack: {0x01}

This pushes a duplicate of the top value onto the stack.
Stack: {0x01, 0x01}

Push an item from the Runtime Constant Pool. In this case, it's a reference to an instance of String representing the literal "xyz". We'll call this one 0x02.
Stack: {0x01, 0x01, 0x02}

This is the String constructor from the object created in line 0 being called. It initializes the new String object using the String object referred to by "xyz".
Stack: {0x01}

This stores the the top stack value (popped) in the first slot of the local variable array.
Variables: {x = 0x01}; Stack: {}

Like before, this pushes an item from the Runtime Constant Pool. This time, it's a reference to an instance of String representing the literal "abc" (0x03).
Variables: {x = 0x01}; Stack: {0x03}

This pops the top stack value, and stores in the second slot of the local variable array.
Variables: {x = 0x01, y = 0x03}; Stack: {}

Create a new StringBuilder object (not initialized yet...). We could think of the new reference as 0x04, but for illustration, I'll show it as a char sequence.
Variables: {x = 0x01, y = 0x03}; Stack: {[]}

Same as before (line 3)...
Variables: {x = 0x01, y = 0x03}; Stack: {[], []}

Initialize the StringBuffer.
Variables: {x = 0x01, y = 0x03}; Stack: {[]}

Loads the first variable onto the stack.
Variables: {x = 0x01, y = 0x03}; Stack: {[], 0x01}

Appends the character sequence represented by 'x' to the StringBuilder object.
Variables: {x = 0x01, y = 0x03}; Stack: {['x','y','z']}

You can probably guess, but this loads the value of the second variable onto the stack.
Variables: {x = 0x01, y = 0x03}; Stack: {['x','y','z'], 0x03}

Appends the character sequence represented by the "abc" literal to the StringBuilder object.
Variables: {x = 0x01, y = 0x03}; Stack: {['x','y','z','a','b','c']}

Calls the toString() method of StringBuilder. You can check the source code, but this creates a new String object on the heap, and pushes a reference to the new String object (we'll call it 0x05).
Variables: {x = 0x01, y = 0x03}; Stack: {['x','y','z','a','b','c'], 0x05}

This stores the the value from the top of the stack into the first variable...
Variables: {x = 0x05, y = 0x03}; Stack: {['x','y','z','a','b','c']}

If this is all the code there is in the method, there will be a return statement following all this, and the stack frame will be popped.

In looking back through this bytecode, we can find four distinct String objects represented by the following references: 0x01, 0x02, 0x03, and 0x05. The StringBuilder object obviously isn't a String, so it doesn't count in our question. Please note that the Runtime Constant Pool holds references to 0x02 and 0x03. These two objects are created when the class gets loaded.

I sincerely hope this helps clear up what's happening in that code, and that my efforts shed some light on the subject.

Good luck!

I'd just add that the behavior described in this post is defined in the JLS and VM specifications I posted earlier. Cheers!
[ November 15, 2005: Message edited by: Steve Morrow ]
 
Jay Pawar
Ranch Hand
Posts: 411
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Steve,
Excellent explanation !!! .
 
Ashok George
Ranch Hand
Posts: 87
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator



STEEEV..........good great explanantion.. great work man... excellent....... :shocked: :shocked: :shocked:


still wondering how ro swim in the ocean of such vast knowledge ocean!!!
great work steev
[ November 16, 2005: Message edited by: Barry Gaunt ]
 
Steve Morrow
Ranch Hand
Posts: 657
Clojure Spring VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks for the feedback, guys. I appreciate it.
 
Akhilesh Trivedi
Ranch Hand
Posts: 1599
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Steve Morrow:


Apparently, I haven't reached "trustworthy" status yet...


Now you should be into the radius of trust....
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic