aspose file tools
The moose likes Java in General and the fly likes Number of object created here Big Moose Saloon
  Search | Java FAQ | Recent Topics
Register / Login


JavaRanch » Java Forums » Java » Java in General
Reply Bookmark "Number of object created here" Watch "Number of object created here" New topic
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
    
    1

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
 
I agree. Here's the link: http://zeroturnaround.com/jrebel - it saves me about five hours per week
 
subject: Number of object created here
 
Similar Threads
can we do it?
String Functions
How we can find that how much string objects has been created?
Number of objects created in StringBuilder ?
question about page scope