Win a copy of The Java Performance Companion this week in the Performance forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

String Doubt

 
pras
Ranch Hand
Posts: 188
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
String s1="pras"
String s2="pras"


here how many objects are created??

is it 2 objects with s1 and s2 referring to each of them or only one with both referring to same object??


String s1="pras"
String s2="abcd"

now how many objects??
 
Bill Shirley
Ranch Hand
Posts: 457
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
s1 and s2 are references to an object,
String classes are immutable

the answer to your question is dependent on the implementation of the JVM (and likely the compiler) - either way, it doesn't matter.
 
Jim Yingst
Wanderer
Sheriff
Posts: 18671
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Well, it's actually guaranteed by the Java Language Specification that in this case, s1 and s2 will refer to the same object. There is only one String object here. However I would agree that in the vast majority of cases, it really doesn't matter.
 
marc weber
Sheriff
Posts: 11343
Java Mac Safari
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Bill Shirley:
...the answer to your question is dependent on the implementation of the JVM (and likely the compiler) - either way, it doesn't matter.

No, this behavior is specified in the JLS and it's important to understanding String references. See 3.10.5 String Literals (especially the points made at the end of this section).

For a more user-friendly explanation, see Strings Literally.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic