This week's book giveaway is in the Kotlin forum.
We're giving away four copies of Kotlin in Action and have Dmitry Jemerov & Svetlana Isakova on-line!
See this thread for details.
Win a copy of Kotlin in Action this week in the Kotlin forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

Doubt in the behaviour of 'String' class!!!  RSS feed

 
Jeraldine Sheeba
Greenhorn
Posts: 8
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi friends,

I have a doubt (May sound simple) regarding the behaviour of the 'String' class.I have 3 programs.

Let me list one by one.

Program :1

public class Test
{
public static void main(String s[ ])
{
String s1 =new String("Hi");
String s2=new String("Hi");
if(s1==s2)
System.out.println("Both are same");
else
System.out.println("Both are different");
}
}

Program : 2

public class Test
{
public static void main(String s[ ])
{
String s1 =new String();
String s2=new String();
s1 = "Hi";
s2 = "Hi";
if(s1==s2)
System.out.println("Both are same");
else
System.out.println("Both are different");
}
}

Program : 3


public class Test
{
public static void main(String s[ ])
{
String s1 = "Hi";
String s2 = "Hi";
if(s1==s2)
System.out.println("Both are same");
else
System.out.println("Both are different");
}
}

The first one prints "Both are different" , but the next 2 two prints "Both are same", I want the exact explanation of this , why is this happening?


Expecting ur replies.......

Regards,
sheeba
 
Jeroen Wenting
Ranch Hand
Posts: 5093
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
== compares the reference variable only, not what is contained in it.
In the first case, you have 2 distinct reference variables, therefore they are not the same.
In the other 2 cases you have only 1 reference variable due to the way Java handles Strings, and therefore the comparison yields true.

Essentially, Strings though Objects behave somewhat like primitives in some contexts but you should never rely on it!

Best get into the habit of never using == to compare Strings (or any other Objects) unless you indeed want to ascertain that the two are indeed pointing to the same exact instance rather than containing the same data.
Use equals() instead.
 
Ernest Friedman-Hill
author and iconoclast
Sheriff
Posts: 24217
38
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

Welcome to JavaRanch!

You need to know two things to understand this:

The "==" operator tests whether two variables point to the same physical object in memory.

A string in a program like "Hi" is called a string literal, and when Java sees a string literal, it creates a String object to represent it. Furthermore, all the identical string literals in the JVM refer to the same physical object -- so in programs 2 and 3, both instances of "Hi" refer to the same physical object. In program 1, the two Strings you create with "new" have the same contents, but they're two separate objects.


The '==' operator tests for the same object, while the "equals()" method asks if two objects are "equivalent"; for Strings, "equivalent" means the same length, and the same characters in the same order. The correct way to compare Strings is usually

if (s1.equals(s2)) ...
 
Jeraldine Sheeba
Greenhorn
Posts: 8
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanx for ur warm welcome into Javaranch...
I am also thankful for ur crstal clear reply.
Thaks a lot

regards,
sheeba
 
Dirk Schreckmann
Sheriff
Posts: 7023
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Jeraldine Sheeba M,

Welcome to JavaRanch!

We ain't got many rules 'round these parts, but we do got one. Please change your display name to comply with The JavaRanch Naming Policy.

I'd like to make one request concerning your display name: We don't fancy having a single letter for the displayed last name. Perhaps you could add more to it, or "Jeraldine Sheeba" would suffice.

Thanks Pardner! Hope to see you 'round the Ranch!
 
Nigel Browne
Ranch Hand
Posts: 704
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Of the three programs the third was the one which programatically is the norm, reusing the string literal and saving memory space.
In program one you are creating three instances of String. By sending a String as an argument to the String constructor using new String("Hi"), you are actually creating two new copies of the String "Hi". So unneccesary object are loaded into memory.
In the second progam two empty instances of String are created before being assigned to the string literal "Hi" again this is bad programming.
 
Tony Morris
Ranch Hand
Posts: 1608
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Furthermore, all the identical string literals in the JVM refer to the same physical object


To clarify a point, which may not be relevant to a beginner's forum (if you don't understand it, don't worry - ignore it).

The above statement is incorrect. Identical String literals in the JVM may or may not refer to the same object. That is, when a String literal is encountered at runtime, a String object is created, and if it becomes eligible for garbage collection, the object may be collected. If some time after, the same String literal is encountered by the JVM, a new String object will be created.

Suffice to say that two String literals in the same scope will be the same object because there is indeed a strong reference to the object (and thus, ineligible for garbage collection).

The Sun and IBM JVM can both be used to prove this assertion.

Apologies if this causes confusion - forget it if this is the case and come back to it another day.
 
Ernest Friedman-Hill
author and iconoclast
Sheriff
Posts: 24217
38
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Tony Morris:
The above statement is incorrect. Identical String literals in the JVM may or may not refer to the same object.


Section 3.20.5 of the Java Language Specification would seem to disagree with you. Literals, which are always stored in the internal string pool, are never garbage collected.
 
Tony Morris
Ranch Hand
Posts: 1608
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I am aware of this clause in the JLS and suggest that this is an ambiguity rather than disagreement. My statement can be proven by the fact that the Sun VM's System.identityHashCode(Object) always returns a unique value for a unique instance (since it uses pointers as object references).

Here is an article I found that does just that: http://www.javaworld.com/javaworld/javaqa/2003-12/01-qa-1212-intern-p2.html

The "String literal pool" is an abstract concept - there is not necessarily a "pool of String literal instances".
[ September 23, 2004: Message edited by: Tony Morris ]
 
Ernest Friedman-Hill
author and iconoclast
Sheriff
Posts: 24217
38
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
There's nothing that stops Sun from implementing a JVM that violates the JLS, as they've apparently done here. Useful information to know, though, in any case.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!