equals( ) Versus == in Java

By: Mashoud Emailed: 1674 times Printed: 2157 times    

Latest comments
By: rohit kumar - how this program is work
By: Kirti - Hi..thx for the hadoop in
By: Spijker - I have altered the code a
By: ali mohammed - why we use the java in ne
By: ali mohammed - why we use the java in ne
By: mizhelle - when I exported the data
By: raul - no output as well, i'm ge
By: Rajesh - thanx very much...
By: Suindu De - Suppose we are executing

It is important to understand that the equals( ) method and the == operator perform two different operations. As just explained, the equals( ) method compares the characters inside a String object. The == operator compares two object references to see whether they refer to the same instance. The following program shows how two different String objects can contain the same characters, but references to these objects will not compare as equal:

// equals() vs ==
class EqualsNotEqualTo {
public static void main(String args[]) {
String s1 = "Hello";
String s2 = new String(s1);
System.out.println(s1 + " equals " + s2 + " -> " +
s1.equals(s2));
System.out.println(s1 + " == " + s2 + " -> " + (s1 == s2));
}
}

The variable s1 refers to the String instance created by "Hello". The object referred to by s2 is created with s1 as an initializer. Thus, the contents of the two String objects are identical, but they are distinct objects. This means that s1 and s2 do not refer to the same objects and are, therefore, not ==, as is shown here by the output of the preceding example:

Hello equals Hello -> true
Hello == Hello -> false


Java Home | All Java Tutorials | Latest Java Tutorials

Sponsored Links

If this tutorial doesn't answer your question, or you have a specific question, just ask an expert here. Post your question to get a direct answer.



Bookmark and Share

Comments(15)


1. View Comment

Thanks for the explanation.
It makes sense. However, I tried this:

String s1 = "Hello";
String s2 = "Hello"; // new String(s1);
System.out.println(s1 + " equals " + s2 + " -> " + s1.equals(s2));
System.out.println(s1 + " == " + s2 + " -> " + (s1 == s2));

and I don't understand the result.
Can someone explain why both result in equal. please?

MJ


View Tutorial          By: Miguel JImenez at 2009-05-10 14:28:46
2. View Comment

When JVM find two string object with de same content, in order to save memory, insted of create two objects, this two objects stay referenced to the same memory location.
I mean, if you have a string "Hello" already created, when you create a new string with the same word "Hello" JVM detect that already exist this string and then did not create a new object, JVM just make a reference the two objects to the same "Hello", so S1 and S2 are "pointing" to the same place in the memory, and S1 == S2 are true


View Tutorial          By: ku at 2009-05-11 10:17:51
3. View Comment

s1==s2 is not true. its false. run the program and check it.

View Tutorial          By: arpita at 2009-05-18 23:50:11
4. View Comment

There is no need to fight. ...whatever ku is saying is correct and what arpita experienced is also correct.
Ku will be correct if I say
String s1 = "Hello";
String s2 = "Hello";
the big difference is here I am not explicitly creating a new object , instead if I had used String s2 = new String ("Hello") just like in thread 1 then I will get s1 == s2 not true which arpita got. Arpita if you try s2 = "Hello" in your program you may get true (depends on your jvm)

One more thing what ku said is JVM specific, a particular JVM can choose to maintain String pool while other may not.
String API just guarantees that equals() will work as intended but not == .


View Tutorial          By: saurabh at 2009-07-30 15:19:49
5. View Comment

i am not sure of this line(depends on your jvm) , can you please explain in detail as how to get the control over the JVM behaviour.

View Tutorial          By: vpeddi at 2010-03-20 07:20:19
6. View Comment

Hello Friends ,

s1 == s2 will always give false . Because s1 == s2 gives refers to the different memory location .

Note that , in java every object refers to the different memory locations. So , == will always give you false.
If we declare s1=s2 then it will give true . While s1.equals(s2) compares the character within the String object . So it will give true.


View Tutorial          By: Gunjan at 2010-09-08 19:24:24
7. View Comment

Hai Guys..
Itâs nice to see your discussion on equals() and == operation
Yes, some older version of JVM having different behavior but in case of string the == will return true (without explicit new key word.) since it immutable nature. Thatâs how itâs working in string pool.
This may useful.

Thanks
Santosh.
You are always welcome.


View Tutorial          By: Santosh at 2010-09-19 08:17:52
8. View Comment

Ku is quite correct. When you create any object, it goes to the string pool. If you are creating again the same object having different reference variable the jvm directly calls it from the pool. It is the property of jvm not to create replica of objects for overhead. Try it, both are true.

View Tutorial          By: Avnish at 2010-10-28 04:00:20
9. View Comment

Its so very helpful

View Tutorial          By: Anurag at 2011-02-08 04:27:03
10. View Comment

Here is my approach for writing equals() method from <a href="http://javarevisited.blogspot.com/2011/02/how-to-write-equals-method-in-java.html">How to write equals method in Java</a>

1) Do this check -- if yes then return true.
2) Do null check -- if yes then return false.
3) Do the instanceof check if instanceof return false than return false
4) Type cast the object; note the sequence instanceof check must be prior to casting object.
5) Compare individual attribute start with numeric attribute because comparing numeric attribute is fast and using short circuit operator so if first field does not match , don't try to match rest of attribute and return false.


View Tutorial          By: Javin @ eclipse remote debugging at 2011-04-09 06:50:44
11. View Comment

what ll be result for s1==s2 and s1.equals(s2) for following cases?
1)String s1="hello";
String s2="hello";

2)String s1 = new String("Hello");
String s2 = new String("Hello");

3)String s1="hello";
string s2=s1;


View Tutorial          By: vijay at 2011-08-21 15:09:41
12. View Comment

Hi,it's really nice to see all the comments of the given topic equals() method and '==' .i would like to share the solution of question asked by Vijay.lets see

result for s1==s2 and s1.equals(s2) for following cases?
1)String s1="hello";
String s2="hello";

->Both equals() and "==" give TRUE

2)String s1 = new String("Hello");
String s2 = new String("Hello");

equals() will give TRUE but "==" will give FALSE

3)String s1="hello";
string s2=s1;

In this case also both will give TRUE bez both pointing to same location

Hope this will help u


View Tutorial          By: sraban at 2011-10-13 12:13:38
13. View Comment

Hi Guys, thanks for sharing this... I have some more doubt.

1. String s1= new String("Hello");
String s2="Hello";

Here, whether s2 will point to the same location as s1?

2. String s1="Hello";
String s2=new String("Hello");

What will be the output of these 2 scenarios?


View Tutorial          By: Fins at 2011-12-14 04:40:09
14. View Comment

import java.util.*;

public class demo {
public static void main(String[] args) {
int q=1;
int r=2-1;
Integer t=new Integer(1);
System.out.println(q==t);
System.out.println(t.equals(r));
System.out.println(q==r);
}
}

Output -

true
true
true

Please give me the explanation.
Many thanks in advance!


View Tutorial          By: Virudada at 2012-05-05 06:27:22
15. View Comment

estimado lo que sucede es que solo cuando es String maneja un pool para que no se duplique los valores y guardar en una sola posicion de memoria el objeto con valor igual

View Tutorial          By: hormiga at 2013-01-07 00:11:54

Your name (required):


Your email(required, will not be shown to the public):


Your sites URL (optional):


Your comments:



More Tutorials by Mashoud
ThreadGroup Sample in Java
Converting Numbers to and from Strings using Java
Using toLowerCase( ) and toUpperCase( ) in Java
How to use regionMatches( ) in Java
startsWith( ) and endsWith( ) in Java
equals( ) Versus == in Java
compareTo( ) in Java
String Conversion and toString() in Java

More Tutorials in Java
Update contents of a file within a jar file
Tomcat and httpd configured in port 8080 and 80
Java File
Java String
Count number of vowels, consonants and digits in a String in Java
Reverse a number in Java
Student marks calculation program in Java
Handling Fractions in Java
Calculate gross salary in Java
Calculate average sale of the week in Java
Vector in Java - Sample Program
MultiLevel Inheritance sample in Java
Multiple Inheritance sample in Java
Java program using Method Overriding
Java program to check if user input is an even number

More Latest News
Most Viewed Articles (in Java )
How to Send SMS using Java Program (full code sample included)
Stack example in Java - push(), pop(), empty(), search()
Method Overriding in Java
FileReader and FileWriter example program in Java
The Basic Structure of a Simple Java program
Read from a COM port using Java program
XML and Java - Parsing XML using Java Tutorial
Using StringTokenizer in Java
How to use ArrayList in Java
Recursion in java
Student marks calculation program in Java
How to use Iterator in Java
Abstract classes in Java
Method Overloading (function overloading) in Java
append() in Java
Most Emailed Articles (in Java)
Tomcat and httpd configured in port 8080 and 80
Update contents of a file within a jar file
Vector in Java - Sample Program
Get user input in Java
FilenameFilter - sample program in Java
How to Send SMS using Java Program (full code sample included)
Count number of vowels, consonants and digits in a String in Java
Java program using Method Overriding
Using StringTokenizer in Java
How to use ArrayList in Java
Using substring( ) in Java
Java File
MultiLevel Inheritance sample in Java
Read a file line by line in Java - Sample Program
The clone() Method in Java