Java String comparison. The difference between == and equals().

Many Java beginners find it difficult to differentiate between == operator and the “equals()” method when comparing String variables in Java. They assume that both operations perform the same function and either one can be used to compare two string variables. I have even seen many experienced programmers committing the mistake of using “==” to compare the values of two strings.

So what is the difference between “==” and “equals()” and what is the correct method of comparing two string variables?

The == operator:

The “==” operator compares the references of two objects in memory. It returns true if both objects point to exact same location in memory. Remember that Strings are immutable in Java, so if you have a String variable str1 with a value of “abc” and then you create another variable str2 with value “abc”, rather than creating a new String variable with same value, Java will simply point str2 to same memory location that holds the value for str1.

In this scenario str1==str2 will return true because both str1 and str2 are referencing the same object in memory.

However, if you create a new variable using the String constructor, like String str3=new String(“abc”); Java will allocate new memory space for str3. Now although str1 and str3 have exact same value, str1==str3 will return false because they are two distinct objects in the memory.

The equals() method:

The equals method compare the text content or the value of two string variables. If both variables have exact same value, equals() will return true, otherwise it will return false.
So, str1.equals(str2) , str1.equals(str3), and str2.equals(str3) will all return true.
str1.equals(“xyz”) will return false.

Here is an example to help you understand the difference between “==” and equals().

public class StringComparison{
	public static void main(String args[]){
		String str1 =  new String("abc");
		String str2 =  new String ("abc");
			System.out.println("str1==str2 is true");
			System.out.println("str1==str2 is false");
			System.out.println("str1.equals(str2) is true");
			System.out.println("str1.equals(str2) is false");
		String str3="abc",
		str4 ="abc";
			System.out.println("str3==str4 is true");
			System.out.println("str3==str4 is false");

Here is the output from this program.

 str1==str2 is false
 str1.equals(str2) is true
 str3==str4 is true

Most of the time you need to compare the values of the variable so you will need the equals() method. In situations where you need to check if two variables reference same memory location then you will use “==” operator.

I hope this will help you understand when to use “==” or equals() for Java string comparison.

Image credit: Martyne

If you enjoyed this post, make sure you subscribe to my RSS feed!

36 Thoughts on “Java String comparison. The difference between == and equals().

  1. Executive Suites New York on April 27, 2010 at 7:09 am said:

    This post is really good I haven’t this problems with C language but I had any problems to differentiate these operators in java, I never have used the function equals() now I will use it. Thanks.

  2. losange165 on June 2, 2010 at 9:56 am said:

    I like this post! 🙂 very good for beginner like me! thanX again!

  3. it is very good post! it helps a lot to a beginner

  4. Most of the time you need to compare the values of the variable

  5. I assumed that both operations perform the same function and either one can be used to compare two string variables but it turns out I was wrong.

  6. its very good ,thanks

  7. Just to add a bit more to this article, the equals() method is often gets overriden in order to set-up for specific comparaaison purpouses that will takes place the on the instances of the class, where the overriding takes place.

    It is still a good article, and if you are likely to do SCJP then most probably you will be questioned about the right use of equals()…

  8. Pingback: I need help with a very simple problem

  9. Is there any opposite function available of equals()?

  10. ?? ?? on July 21, 2011 at 12:52 pm said:

    @Zamshed: try the ! operator

  11. Sohail on August 9, 2011 at 7:12 am said:

    >> str4 =”abc”;
    Shouldn’t it be: String str4 =”abc”; ?

    Or is it that I am missing something here?

  12. Sohail on August 9, 2011 at 7:15 am said:

    OK got it, I missed the presence of comma in the previous line 🙂

  13. Thanks a lot..very clear explanation than other posts in internet on the same issue.

  14. Thank you so much for a great explanation. It is a great help to the beginners. I would like to add the following lines to the explanation as well:

    equals() and hashcode() methods are from Cosmic super class Object from Java.lang package and hence they’re the one’s those are overridden most of the times.

    Do let me know if I’m wrong…

    Thanks and Regards,


  15. String s1=”abc”;

    System.out.println(“Both are Equal”);

    System.out.println(“Both are not Equal”);

    Output:- Both are Equal

    How this can Happen can any one please explain ?

  16. I haven’t looked at the Java source code, but my educated guess is that the Java run time is placing all the constant strings (i.e. “abc”) at specific locations in memory, and then assigning the pointers (i.e. s1) to point to those locations. Both of the “abc” constants, being equal, would (as a optimization) be assigned to the same location, Since s1 was assigned to point to that location, s1 == “abc” will be true. If you built up the string “abc” in another fashion, this would not be the case,


  17. Ok, the equals() method makes sense, but what if you cant use the == or <= to compare a variable? How do you use equals() to test a range of values, assuming you can at all?

  18. Nascar on October 1, 2011 at 12:28 am said:


    Thanks for the post. I am just a beginner in Java.

    I need to know how to validate multiple values for a string.
    like, if the value of month is not equal to J or F or M, perform some error handling.
    The requirement is: J, F and M are the expected (good) values for month.

    Example: If (!month.equals(“J”) || !month.equals(“F”) || !month.equals(“A”)) {
    Perform error validation;

    Is the above correct?

    Any help is appreciated. Thanks

  19. Nascar on October 1, 2011 at 1:02 am said:

    Or can we say?
    If (!month.equals(“J”, “F”,“A”)) {
    Perform error validation;

  20. Pajarito on October 21, 2011 at 5:18 am said:

    So, what is the diff between:

    String a = “abc”;
    String a = new String(“abc”);

    Beacuse “everything in Java is an object” the first one above is an object of String class, the same as the latter. Is there any difference?

  21. Praveen on November 16, 2011 at 5:47 am said:

    Before reding your post i had confision to use these operators. Now i got clear idea. Thanks for your post..

  22. Leo Nardus on November 23, 2011 at 2:40 pm said:

    Hi .. Thanks mate for your posting ..
    It’s help me a lot 😀 ..
    Love it ..

  23. sandesh on January 26, 2012 at 4:05 am said:

    thanx a lot ……… i was breaking my head as i did the same mistake of confusing == ……..
    your article helped ………

  24. Erinyes on January 30, 2012 at 8:07 am said:

    Wow, I never knew that _this_ is the difference between both compare operations. Thanks for the info! Much appreciated 😀

  25. For More info on this topic you can also see

    Difference Between == and ===

  26. Hi.. i really like this post. Before i couldn’t see like that. thanks

  27. spremusik on May 10, 2012 at 1:18 am said:

    very good example. it helped me alot. thx

  28. burros do caralho isto n ajuda nada fdps de merda dum cano

    Ass: Orelhas

  29. Venho por este meio, vos dizer outravez que tou farto desta porra de vida. O java já não faz sentido, tou farto de andar a coçar na micose todo dia em casa, tenho k começar a procurar emprego no macmenuts a trabalhar na, este site nem pa imprimir na minha t-shirt serve….. Axo que vou masé comprar um barco, ou n, talvez vou entrar na profissional outravez pa comprar adesivo da base pa colar a carrinha do meu pai.
    Ainda venho por este meio, tentar concretizar os meus sonhos de forma a servir de exemplo para todos os gorilas deste site.
    Esta selva não vale um PEIDO, um PEIDO fodasse manizzle.

  30. Bom afternoon,

    Primeiro era pa dizer que fiz uma aposta ontem no benfica e perdi. Senti a necessidade de vir cá expressar a minha raiva.

  31. wtf?? on May 29, 2012 at 4:29 pm said:

    Why does Java make simple things complicated?

    Why not make classes to overload == operation, and use === for references comparison?

  32. Satyendra Mishra on June 4, 2012 at 11:53 pm said:

    really awesome example

  33. This should sit at the very root of any programming tutorial. It helped me understand the differences immediately. Thanks a million!

  34. I read a lot of interesting articles here. Probably you spend a lot of time writing, i know how
    to save you a lot of work, there is an online tool that
    creates readable, SEO friendly posts in minutes, just type in google – laranitas free content source

  35. This is the pecerft post for me to find at this time

  36. geet on May 25, 2016 at 1:26 am said:

    Hi, This is very Useful to me now i understood very well,


Leave a Reply

Your email address will not be published. Required fields are marked *

Post Navigation