Win a copy of Clojure in Action this week in the Clojure forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Number of object created here

 
Kaustubh G Sharma
Ranch Hand
Posts: 1283
Chrome Java Netbeans IDE
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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 ??
 
Rob Spoor
Sheriff
Pie
Posts: 20380
46
Chrome Eclipse IDE Java Windows
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
Kaustubh G Sharma
Ranch Hand
Posts: 1283
Chrome Java Netbeans IDE
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Pie
Posts: 20380
46
Chrome Eclipse IDE Java Windows
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Pie
Posts: 4835
34
Chrome Netbeans IDE Windows
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
And that's not even counting the objects StringBuilder is composed of!
 
Kaustubh G Sharma
Ranch Hand
Posts: 1283
Chrome Java Netbeans IDE
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
got it Thanks guys
 
I agree. Here's the link: http://aspose.com/file-tools
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic