aspose file tools*
The moose likes Beginning Java and the fly likes == and .equals Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "== and .equals" Watch "== and .equals" New topic
Author

== and .equals

nagul samy
Ranch Hand

Joined: Feb 15, 2012
Posts: 37
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

Joined: Jan 28, 2008
Posts: 5575

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

Joined: Dec 08, 2010
Posts: 1510
    
    5

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.


Regards,
Anayonkar Shivalkar (SCJP, SCWCD, OCMJD, OCEEJBD)
nagul samy
Ranch Hand

Joined: Feb 15, 2012
Posts: 37
Thanks Guys........
James Boswell
Bartender

Joined: Nov 09, 2011
Posts: 1030
    
    5

and here randomValue and CUSTOMER_MOBILE_CONTACT are equal


They are equal in value perhaps but they do not refer to the same object.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: == and .equals