string problem

Rippon Jalali

Greenhorn

Posts: 23

posted 10 years ago

the below given code gives "Not Equal". But as trim() returns a string whose value is string used to invoke the method but with any leading or trailing blank spaces removed. So isn't the condition result in true and output be "Equal"?

if(" String ".trim() == "String")

System.out.println("Equal");

else

System.out.println("Not Equal");

Sundeep Gupta

Greenhorn

Posts: 13

posted 10 years ago

When you try to compare two strings using ==, Java compares thier object references and result will be false, even if lexically the strings are equal. This is because Strings in Java are immutable and hence separate object is created for each string. To compare two strings lexically, use equals() method.

SCJP 5.0

Rippon Jalali

Greenhorn

Posts: 23

posted 10 years ago

but when we are comparing string literals there is no need of equals method.As when we run the code below.it gives output "Equal". if("String".toString() == "String")