• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

how many String objects are created?

 
rani bedi
Ranch Hand
Posts: 358
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

I reckon four String objects were created - "java", "exam", " ", "java exam"? Is it true?
 
Nick Shrine
Greenhorn
Posts: 11
Hibernate Netbeans IDE Tomcat Server
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I'd say 6 (but I'm not sure), here's why:
The objects "java", "exam" and " " are created in the string constant pool, the objects pointed to by the references s1 and s2 are created on the heap and the String object created by the addition (s1 + " " + s2) is created on the heap so you have 3 objects in the string constant pool and 3 on the heap, but I'm just guessing as I'm not sure what really goes on when you create a String with the overloaded "=" operator. Perhaps s1 and s2 point to objects in the constant pool rather than the heap? Can anyone clarify?
Nick
 
Nick Shrine
Greenhorn
Posts: 11
Hibernate Netbeans IDE Tomcat Server
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I've changed my mind, I think it's 4.
If the overloaded "=" operator creates objects on the heap then there is no point in having a String constant pool to save memory, so I reckon s1 and s2 point to objects in the constant pool, so there's 3 in the pool and 1 on the heap (the one made by the addition) - err or does that one go in the pool too?
Anyway I say 4
Nick - realised he doesn't understand how Strings work
 
Alex Radomski
Greenhorn
Posts: 24
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,
I'd say three String objects are created, Correct me if I'm wrong?


[ August 13, 2003: Message edited by: Alex Radomski ]
 
rani bedi
Ranch Hand
Posts: 358
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I reckon four String objects were created - "java", "exam", " ", "java exam"
 
Yi Meng
Ranch Hand
Posts: 270
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

I would say that there are THREE string objects created during the compile time, "java", "exam", " " and one string object created at runtime, "java exam".
However, if you declare s1 and s2 as final, then there would still THREE string objects created during compile time, but they are "java", "exam" and "java exam". And there will be no objects created at runtime.
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic