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 IamaSherpa on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

String comparasions with == 1

Status
Not open for further replies.

KillerProgrammer

Programmer
Oct 25, 2002
3
BR
In the following code , why case 1 and case 3 returns "Not Equals" and case 2 returns "Equals" . The reference variable in case 1 is not the same from the string "String" in the JVM String Pool ? If not , case 2 should return "Not equals" , don't ? Same for case 3 that , in my way , should be identic to the case 1

public class Test
{
public static void main(String[] args)
{
//case 1
if(" String ".trim() == "String")
System.out.println("Equals");
else
System.out.println("Not Equals");

//case 2
if("String".substring(0) == "String")
System.out.println("Equals");
else
System.out.println("Not Equals");

//case 3
if(" String ".substring(1,7) == "String")
System.out.println("Equals");
else
System.out.println("Not Equals");

}
}

TIA

Thor
 
The bottom line is you should never use '==' on Strings unless you are wanting to compare Object references. Any other behavior you see is likely "undefined' and may change from VM to VM.

To find string equality you must use equals() and equalsIgnoreCase() etc.

-pete
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top