• Post Reply Bookmark Topic Watch Topic
  • New Topic

String problem  RSS feed

 
Vijay Chandran
Ranch Hand
Posts: 186
Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator


Dear friends,

Why the output is "Not Equal"? even after trimming.


Kindly provide your help.

Regards,
Vijay
 
Ulf Dittmer
Rancher
Posts: 42972
73
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
String equality is not tested with the "==" operator, it is tested using the "equals" method. What you're testing is object equality, which is very different from the strings having the same characters.
 
Raghavan Muthu
Ranch Hand
Posts: 3389
Mac MySQL Database Tomcat Server
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
It is because .equals() method only checks for the 'content equality' but the == operators checks for the references to string objects.
 
yan yan
Greenhorn
Posts: 16
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
In your code example, there are two words are found: " String " & "String"
found in the string pool because you are using the "==" you are comparing the two locations, thus the output is "not equal."
declaring two variable with the same value. Only one "String" is found
in the string pool, thus only one location/reference.

public class Test1
{
public static void main(String[] args)
{
String abc = "String";
String cde = "String";
if(abc.equals(cde))
System.out.println("Equal");
else

System.out.println("Not Equal");
}
}
 
Venkat Kanneganti
Ranch Hand
Posts: 43
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,
here '=='
checks either objects have same memory location or not
thats why "string".trim(),"string" objects are in different locations so '=='
returns false,where equals() method for strings compare contents of string objects thats why if you use equals() method instead of '==' result is true
i think he will clear from this
Bye
Venkat
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!