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 compares 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");
if(str1==str2){
System.out.println("str1==str2 is true");
}else{
System.out.println("str1==str2 is false");
}
if(str1.equals(str2)){
System.out.println("str1.equals(str2) is true");
}else{
System.out.println("str1.equals(str2) is false");
}
String str3="abc",
str4 ="abc";
if(str3==str4){
System.out.println("str3==str4 is true");
}else{
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
Executive Suites New York
April 27, 2010 @ 7:09 am
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.
losange165
June 2, 2010 @ 9:56 am
I like this post! 🙂 very good for beginner like me! thanX again!
Nag
June 21, 2010 @ 11:45 pm
it is very good post! it helps a lot to a beginner
??? ??????
August 7, 2010 @ 9:37 am
Most of the time you need to compare the values of the variable
Woodlands Divorce Attorney
October 19, 2010 @ 12:01 pm
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.
Neelu
November 10, 2010 @ 6:39 am
its very good ,thanks
Sefi
February 11, 2011 @ 8:04 am
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()…
I need help with a very simple problem
July 2, 2011 @ 11:37 pm
[…] import java.util.Scanner; import java.util.Random; public class Program { public static void main(String[] args){ Scanner keyboard = new Scanner(System.in); //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(). […]
Zamshed Farhan
July 19, 2011 @ 1:40 am
Is there any opposite function available of equals()?
?? ??
July 21, 2011 @ 12:52 pm
@Zamshed: try the ! operator
Sohail
August 9, 2011 @ 7:12 am
>> str4 =”abc”;
Shouldn’t it be: String str4 =”abc”; ?
Or is it that I am missing something here?
Sohail
August 9, 2011 @ 7:15 am
OK got it, I missed the presence of comma in the previous line 🙂
Lipon
August 10, 2011 @ 2:40 am
Thanks a lot..very clear explanation than other posts in internet on the same issue.
Ashish
September 12, 2011 @ 5:17 am
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,
Ashish
Naveen
September 26, 2011 @ 7:28 am
String s1=”abc”;
if(s1==”abc”){
System.out.println(“Both are Equal”);
}else{
System.out.println(“Both are not Equal”);
}
Output:- Both are Equal
How this can Happen can any one please explain ?
Tom N.
September 26, 2011 @ 2:22 pm
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,
Tom
Robert
September 30, 2011 @ 1:07 pm
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?
Nascar
October 1, 2011 @ 12:28 am
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
Nascar
October 1, 2011 @ 1:02 am
Or can we say?
If (!month.equals(“J”, “F”,“A”)) {
Perform error validation;
}
Pajarito
October 21, 2011 @ 5:18 am
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?
Praveen
November 16, 2011 @ 5:47 am
Before reding your post i had confision to use these operators. Now i got clear idea. Thanks for your post..
Leo Nardus
November 23, 2011 @ 2:40 pm
Hi .. Thanks mate for your posting ..
It’s help me a lot 😀 ..
Love it ..
sandesh
January 26, 2012 @ 4:05 am
thanx a lot ……… i was breaking my head as i did the same mistake of confusing == ……..
your article helped ………
Erinyes
January 30, 2012 @ 8:07 am
Wow, I never knew that _this_ is the difference between both compare operations. Thanks for the info! Much appreciated 😀
Vishal
February 17, 2012 @ 5:53 am
For More info on this topic you can also see
Difference Between == and ===
spremusik
May 10, 2012 @ 1:18 am
very good example. it helped me alot. thx
rebeca
May 21, 2012 @ 9:54 am
burros do caralho isto n ajuda nada fdps de merda dum cano
Ass: Orelhas
rebeca
May 22, 2012 @ 8:34 am
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.
rafa a.k.a nelse
May 22, 2012 @ 8:39 am
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.
wtf??
May 29, 2012 @ 4:29 pm
Why does Java make simple things complicated?
Why not make classes to overload == operation, and use === for references comparison?
Satyendra Mishra
June 4, 2012 @ 11:53 pm
really awesome example
Mitran
October 17, 2012 @ 10:54 am
This should sit at the very root of any programming tutorial. It helped me understand the differences immediately. Thanks a million!
Mariano
September 19, 2014 @ 6:42 am
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
Welcome
May 2, 2016 @ 8:21 pm
This is the pecerft post for me to find at this time
geet
May 25, 2016 @ 1:26 am
Hi, This is very Useful to me now i understood very well,
Thanks.
calculador de credito procrear
October 25, 2016 @ 2:42 pm
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.
foroninja.com
October 26, 2016 @ 6:51 pm
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.
priya
March 21, 2018 @ 4:55 am
Immutable means Not changeable. All Java variables are by default mutable. An Object is immutable if there is no way you can change its fields after it has been constructed.