• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

String problem

 
Ranch Hand
Posts: 186
Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator


Dear friends,

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


Kindly provide your help.

Regards,
Vijay
 
Rancher
Posts: 43081
77
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
 
Ranch Hand
Posts: 3389
Mac MySQL Database Tomcat Server
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
 
Greenhorn
Posts: 16
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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");
}
}
 
Ranch Hand
Posts: 43
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
 
reply
    Bookmark Topic Watch Topic
  • New Topic