aspose file tools*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes how many String objects are created? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of EJB 3 in Action this week in the EJB and other Java EE Technologies forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "how many String objects are created?" Watch "how many String objects are created?" New topic
Author

how many String objects are created?

rani bedi
Ranch Hand

Joined: Feb 06, 2001
Posts: 358

I reckon four String objects were created - "java", "exam", " ", "java exam"? Is it true?


Cheers,<br />Rani<br />SCJP, SCWCD, SCBCD
Nick Shrine
Greenhorn

Joined: Jul 17, 2003
Posts: 11
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<br />SCJP<br />SCJD
Nick Shrine
Greenhorn

Joined: Jul 17, 2003
Posts: 11
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

Joined: Apr 24, 2003
Posts: 24
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

Joined: Feb 06, 2001
Posts: 358
I reckon four String objects were created - "java", "exam", " ", "java exam"
Yi Meng
Ranch Hand

Joined: May 07, 2003
Posts: 270

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.


Meng Yi
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: how many String objects are created?
 
Similar Threads
String Objects
please help me
Strings
help on strings urgent exams next week
String objects creation