jQuery in Action, 2nd edition*
The moose likes Java in General and the fly likes Number of object created here Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Java in General
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: 1270

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: 19651
    
  18

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 - OCEEJBD 6
How To Ask Questions How To Answer Questions
Kaustubh G Sharma
Ranch Hand

Joined: May 13, 2010
Posts: 1270

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: 19651
    
  18

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: 3594
    
  14

And that's not even counting the objects StringBuilder is composed of!
Kaustubh G Sharma
Ranch Hand

Joined: May 13, 2010
Posts: 1270

got it Thanks guys
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Number of object created here
 
Similar Threads
How we can find that how much string objects has been created?
Number of objects created in StringBuilder ?
String Functions
can we do it?
question about page scope