Win a copy of Mesos in Action this week in the Cloud/Virtualizaton forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

== and .equals

 
nagul samy
Ranch Hand
Posts: 37
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi All....

Hope you people are doing well.............

I have the idea of == and .equals method... == is used to compare object reference and .equals method is used to compare object value.....
for example:

String s1 = "apple";
String s2 = "apple";

String s3 = new String("apple");
String s4 = new String("apple");

System.out.println(s1==s2);---------->true
System.out.println(s1.equals(s2));--------->true
System.out.println(s3==s4);---------->false
System.out.println(s3.equals(s4));------------>true

In this case s1 and s2 values will be stored in string pool so the case 1 is true..... and when i run the following code in servlet

String randomValue = request.getParameter("randomValue");
String CUSTOMER_MOBILE_CONTACT = request.getParameter("CUSTOMER_MOBILE_CONTACT");

and here randomValue and CUSTOMER_MOBILE_CONTACT are equal

if(randomValue == CUSTOMER_MOBILE_CONTACT)--------->this returns false why???
i hope .getParameter method returns String.........

please explain me???

 
Seetharaman Venkatasamy
Ranch Hand
Posts: 5575
Eclipse IDE Java Windows XP
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
nagul wrote:if(randomValue == CUSTOMER_MOBILE_CONTACT)--------->this returns false why???

it shows getParameter returns a *new* String Object. use equals method.
 
Anayonkar Shivalkar
Bartender
Posts: 1557
5
Eclipse IDE Java Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi nagul samy,

You should use == operator only when you really need it (i.e. when you are interested not only in contents of objects referred by two references, but you want to make sure that both references refer to same object).

To be on safer side, never, ever use == operator with immutable objects (e.g. String).

I hope this helps.
 
nagul samy
Ranch Hand
Posts: 37
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks Guys........
 
James Boswell
Bartender
Posts: 1051
5
Chrome Eclipse IDE Hibernate
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
and here randomValue and CUSTOMER_MOBILE_CONTACT are equal


They are equal in value perhaps but they do not refer to the same object.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic