aspose file tools*
The moose likes Beginning Java and the fly likes String Doubt Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "String Doubt" Watch "String Doubt" New topic
Author

String Doubt

pras
Ranch Hand

Joined: Apr 04, 2007
Posts: 188
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

Joined: Nov 08, 2007
Posts: 457
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.


Bill Shirley - bshirley - frazerbilt.com
if (Posts < 30) you.read( JavaRanchFAQ);
Jim Yingst
Wanderer
Sheriff

Joined: Jan 30, 2000
Posts: 18671
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.


"I'm not back." - Bill Harding, Twister
marc weber
Sheriff

Joined: Aug 31, 2004
Posts: 11343

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.


"We're kind of on the level of crossword puzzle writers... And no one ever goes to them and gives them an award." ~Joe Strummer
sscce.org
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: String Doubt