Win a copy of The Little Book of Impediments (e-book only) this week in the Agile and Other Processes forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Number of String objects created

 
Thomas Hauck
Ranch Hand
Posts: 95
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator



For the code listed above, I have made the following observations:

1. The code on line 1 creates a new String object with the value "Day".
This object is not placed in the String constant pool.
2. The code at line 2 creates a new String object with the value "Day" which is placed in the String constant pool.
3. The code at line 3 does not need to create any new String object. It reuses the String object with the value "Day" that already existed in the String constant pool.
4. The code at line 4 creates a new String object with the value "night" and places it in the String constant pool.
5. The code at line 5 reuses the String value "night" from the String constant pool.
It creates a String object with the value "day" in the String constant pool because it is lower case (day is different than Day).
6. The code at line 6 creates a new String object with the value "Day".

Conclusion:
The code in the class DayNight creates a total of five String objects.


Please verify.

 
Bill Clar
Ranch Hand
Posts: 163
Eclipse IDE Java Tomcat Server
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Have you ran javap on your program to verify your findings?
 
Aki Mohan
Ranch Hand
Posts: 99
Eclipse IDE Firefox Browser Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hey Thomas,

Yes it creates 5 objects and your observation is right.
 
Roel De Nijs
Sheriff
Posts: 10662
144
AngularJS Chrome Eclipse IDE Hibernate Java jQuery MySQL Database Spring Tomcat Server
  • Likes 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
This article will probably answer your question and will result in a change of your 1st observation (regarding the String constant pool).
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic