| Author |
Number of object created here
|
Kaustubh G Sharma
Ranch Hand
Joined: May 13, 2010
Posts: 1160
|
|
String s ="a";
s= s+"b"+"c";
question is been asked how many objects is been created here...
I said 4
They said no it's 5
Can anyone here explain me how ??
|
No Kaustubh No Fun, Know Kaustubh Know Fun..
|
 |
Rob Spoor
Sheriff
Joined: Oct 27, 2005
Posts: 19232
|
|
It's 5. Theoretically, that's because you don't have one String concatenation but two; s + "b" + "c" should be read as ((s + "b") + "c"). So the Strings:
- "a"
- "b"
- "c"
- "ab" (from s + "b")
- "abc" (from s + "b" + "c')
In practice it's also 5 but because of another reason. The compiler turns String concatenations into a StringBuilder. I've compiled and decompiled (with JAD) your example, and this is the result:
That's still 5 objects:
- "a"
- "b"
- "c"
- the StringBuilder
- "abc", as a result of calling toString() on the StringBuilder
|
SCJP 1.4 - SCJP 6 - SCWCD 5
How To Ask Questions How To Answer Questions
|
 |
Kaustubh G Sharma
Ranch Hand
Joined: May 13, 2010
Posts: 1160
|
|
|
Thanks Rob but here we're not creating any object all we have is reference and string so where're the objects?
|
 |
Rob Spoor
Sheriff
Joined: Oct 27, 2005
Posts: 19232
|
|
|
Every String literal is an object, so that's already three. I clearly see the word "new" there with the StringBuilder, so that's another one. And StringBuilder.toString() returns a new String object containing the same characters as the StringBuilder, so that's five.
|
 |
Stephan van Hulst
Bartender
Joined: Sep 20, 2010
Posts: 3065
|
|
|
And that's not even counting the objects StringBuilder is composed of!
|
 |
Kaustubh G Sharma
Ranch Hand
Joined: May 13, 2010
Posts: 1160
|
|
got it Thanks guys
|
 |
 |
|
|
subject: Number of object created here
|
|
|