• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

String Doubt

 
srinivas sridaragaddi
Ranch Hand
Posts: 225
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

Given the following,
13. String x = new String("xyz");
14. y = "abc";
15. x = x + y;
how many String objects have been created?
A. 2
B. 3
C. 4
D. 5


answer is C. but whether y is considered as a string object or not
no of objects
first one "x"
second "xyz"
third"abc"
fourth "y"
fifth "xyzabc"

i believe should be D

Thanks in advance
 
yong huang
Greenhorn
Posts: 7
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,
My understanding is that Y is not created here but earlier.
 
srinivas sridaragaddi
Ranch Hand
Posts: 225
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Yong,

I thought when we assign value to y it would also be assigned the same value and created again.

that is the reason why x when reassigend with a new value a new string is crerated. or a new string is created only when we use the keyword "new" and updations on this would lead to a new string. correct me if i am wrong.

Thanks in advance

 
Prashant pai
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hi srinivas,
x is just a reference which was pointing to "xyz" string object and it is now pointing to a new string object "xyzabc".
y is also a reference and is now pointing to new string object "abc".
As you must be knowing ,Strings are immutable so when ever you change its value , the reference points to a new object(here in our case "xyxabc").
hope this would help you ..
 
yong huang
Greenhorn
Posts: 7
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi srinivas,
I think the reason "xyzabc" as a new object is because of the the "+" operation but not the assignment operation.
How do you think about it?
I read the chapter in K&B, but couldn't find the page now. Anybody else can help to explain in detail?
Thanks
 
srinivas sridaragaddi
Ranch Hand
Posts: 225
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

Thanks prashanth for solving the problem. i was wrongly counting reference as a new string being created.

ThAnKs
 
Ashish Yannam
Greenhorn
Posts: 19
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
HI,

But what's the final answer,
Please explain me how and where is the fourth object formed.
I think only 3 objects are formed, Please correct me if I am going wrong.
 
neeraj nandwana
Greenhorn
Posts: 6
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
this will make you more clear.

13. String x = new String("xyz"); //2 object(one is refer by x and second is placed in pool)
14. y = "abc";//1 object
15. x = x + y;//1 object


total 4 object created.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic