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!

Comments 40

  • 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.

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

  • it is very good post! it helps a lot to a beginner

  • Most of the time you need to compare the values of the variable

  • 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.

  • its very good ,thanks

  • 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()…

  • […] import java.util.Scanner; import java.util.Random; public class Program { public static void main(String[] args){ Scanner keyboard = new Scanner(; //scanner variable to get user input String option; System.out.println("Welcome!"); System.out.print("Do you want to play the game?"); option = keyboard.nextLine(); //storing input. if(option.equals("Yes") || option.equals("yes")){ System.out.println("Ok then!!! Lets play!"); } else{ System.out.println("n"); System.out.println("Alright! bye!"); } } } Java String comparison. The difference between == and equals(). […]

  • Is there any opposite function available of equals()?

  • @Zamshed: try the ! operator

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

    Or is it that I am missing something here?

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

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

  • 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,


  • 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 ?

  • 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,


  • 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?

  • Hi,

    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

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

  • 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?

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

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

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

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

  • For More info on this topic you can also see

    Difference Between == and ===

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

  • very good example. it helped me alot. thx

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

    Ass: Orelhas

  • 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.

  • 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.

  • Why does Java make simple things complicated?

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

  • really awesome example

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

  • 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

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

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


  • I nearly always recommend the historical books I “review” as something schools ought to use, because the author has just made a period in history sound so interesting, and made it come alive, in a way that teachers never quite manage. And these days schools only seem to do WWII.

  • I really liked the four sentences about personal style!And I loved all the pictures, too. Mainly the first one, the shirt and the first black dress (is so beautiful).

  • A ver, los médicos lo hacéis todo perfecto para los que nos da miedito el tema de quirófano, entendido? La viñeta COJONUDA. Y los comentarios de shora buenísismos.Macho contigo da gusto.

  • In truth, Rog, I had to detach myself for my sanity. As rude as she was, I was allowing her to suck me into her negativity. Once I took a step back, I could see her more clearly… and see this was her issue, not mine. Plus, an actress would have a blast playing a bitch like that – heehee.

Leave a Reply

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