File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
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

== 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");


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");

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

Joined: Dec 08, 2010
Posts: 1545

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.

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

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

Joined: Nov 09, 2011
Posts: 1051

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:
subject: == and .equals
jQuery in Action, 3rd edition