Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Java String class 2

Status
Not open for further replies.

Enea

Technical User
Feb 23, 2005
90
US
I am new to Java. I read the following: do not use the == operators to determine if strings are equal. It only returns true if the strings are stored in the same location.

So..I opened Eclipse and tried the following with 2 ways of testing equality:

public class TestingStrings {
public static void main(String[] args) {
String x="I love Java";
String y="I love Java";

System.out.println(x.equals(y));

if(x==y){
System.out.println("Strings are equal");
}
else
System.out.println("Strings are not equal");
}
}

WHAT I GET IS:
true
Strings are equal

Why am I getting true? Should it be false, based on what I read?
 
What it means is the the == operator is not guaranteed to return true for two strings which happen to have the same textual content.

My understanding is that Java does some stuff 'under the hood' with Strings to try to optimise memory usage. == will return true for Strings with the same content most of the time. I have seen code where it doesn't. (This code compared Strings which came in from outside the JVM - i.e. across a network, with others inside the JVM).

I tend to use the compareTo methods of String since this compares them lexicographically and can be relied on. However, it is many times slower than ==.

I wouldn't like to say when it is safe to assume == will work. Maybe someone else here has a stronger grasp of the internals of Strings and can give the OP a better answer.

Tim
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top