Difference between "== operator" and "equals() method" in java?
HTML-код
- Опубликовано: 9 сен 2024
- DURGASOFT is INDIA's No.1 Software Training Center offers
online training on various technologies like JAVA, .NET ,
ANDROID,HADOOP,TESTING TOOLS , ADF, INFORMATICA, SAP...
courses from Hyderabad & Bangalore -India with Real Time Experts.
Mail us your requirements to durgasoftonlinetraining@gmail.com
so that our Supporting Team will arrange Demo Sessions.
Ph:Call +91-8885252627,+91-7207212428,+91-7207212427,+91-8096969696.
durgasoft.com
durgasoftonline...
/ durgasoftware
durgajobs.com
/ durgajobsinfo.... .
Just gotta say. For some people in the USA, you won't understand 80% of the words that come out of this man's mouth. But from the 20%, I could grasp I got a good understanding of the material. Don't write off this video because of the accent, you can still gain some knowledge from this. Thanks for the explanation!
You are the top instructor for Java. I've been watching your videos for the past week and now I am able to cover all the interview-related questions, which has made me confident. Thank you sir, for providing the best playlist that nobody has done so far.
Great explanation.
I would like to add one point.
when equals method until and unless not overridden it will still compare the address and not the values.
You said opposite because in String classes it is overridden so it chacks the xontents of both the objects but in StringBuffer it equals method is not overriden so it uses reference comparison.
@@Rohit-tz6gs right
Watching his videos from USA 🇺🇸
Great explanation. But the accent is a big struggle for non-indians.
+okeyxyz
Demo Sessions on youtube,
Language Fundamentals(16 Videos)ruclips.net/video/eTXd89t8ngI/видео.html,
Operators & Assignments(7 Videos)ruclips.net/video/1JGOPhIyhAM/видео.html,
Flow Control(6 Videos)ruclips.net/video/X6rS9vD9-qM/видео.html.
it's even a struggle for most Indians. :p
brushupmyskill. com
Samaj ne valoonko eshare kafee hai, aur accent kya cheez aaa!!!
I think I only understood every 10th word but it was still a better explanation than most!
String s1="Durga";
String s2="Durga";
in this case s1==s2 will give us true
that's because in java Strings are immutable, so if you create another object String with the same content, lets say "Durga" again, points directly to the object String created before, because you're not creating a new object but a new reference. So now, if you change both contents "Durga" (because Strings don't change) the originally String object "Durga" will be destroy by the pool Strings Java has.
Here is one thing you should keep in mind -
now as per according to your ques both s1 and s2 are now in same memory called as String Pool.
Note-All String stored in same memory called "String Pool " but except if you use "new" keyword (like in s1 and s2 ) eg-
String s1=new String("hi");
String s2=new String("hi");
String s3="hi";
String s4="hi";
Now both s1,s2 are stored in heap memory that is s1 pointing to one object and s2 pointing to another different object (stored in heap), so content is same but the reference is different but s3 and s4 are stored in the string pool.
Hence, s3 and s4 pointing to same memory that is String pool and has same content "durga" so as a result == and .equals(), both will check same content, Give output as true (but not in the case of new (that is in heap memory)).
Hope you got this keep learning.
@@ArjunSingh-qt5jn wow
in this video both tow answer is true
In this case s1==s2 is true and s1.equals(s2) also true?
Great tutorial and very important question explained in detail. Thank you for your efforts.
+Michael Tirkey
Demo Sessions on youtube,
Language Fundamentals(16 Videos)ruclips.net/video/eTXd89t8ngI/видео.html,
Operators & Assignments(7 Videos)ruclips.net/video/1JGOPhIyhAM/видео.html,
Flow Control(6 Videos)ruclips.net/video/X6rS9vD9-qM/видео.html.
I wish this guy taught me java, fantastic
+MeIsMe Fanx
Demo Sessions on youtube,
Language Fundamentals(16 Videos)ruclips.net/video/eTXd89t8ngI/видео.html,
Operators & Assignments(7 Videos)ruclips.net/video/1JGOPhIyhAM/видео.html,
Flow Control(6 Videos)ruclips.net/video/X6rS9vD9-qM/видео.html.
I don't know hindi but I understood... in a few seconds he explaind it all
Anna no one can teach java like u 😀
Crystal clear. Thank you very much
My question is if interviewer asks the difference between == and .equals()
how can it be specific to String scenario. In StringBuffer .equals() don't act as content comparison because it doesn't override the parent Object class where as in String .equals() overrides parent Object class. So, that means equals() in root/Object class isn't meant for content comparison but for reference comparison, but String overrides it for it's own class implementation. Why are we saying equals() do content comparison? It does content comparison only for String datatypes and for the rest it does ref. comparison!!
awesome teaching and thankyou so much for these helpful videos,really appreciate your effort!
thankyou sir your classes is very useful ayyayi sir naku very thank you sir 🙏
your explanation is great. Thank you! Big like for you, sir
+Hoang Quoc Cuong
Demo Sessions on youtube,
Language Fundamentals(16 Videos)ruclips.net/video/eTXd89t8ngI/видео.html,
Operators & Assignments(7 Videos)ruclips.net/video/1JGOPhIyhAM/видео.html,
Flow Control(6 Videos)ruclips.net/video/X6rS9vD9-qM/видео.html.
such a good way to explain . sir u cleared my doubt. thanks sir
Sir , I am your student . I am in a position because of you. Thanks a lot sir. i have small doubt. We are using String class equals for content comparison . How it is useful to other objects . How can we override content for non String objects. In that case How equals method is useful. Sorry if my thinking was wrong.
For immutable objects equals method is always true and for mutable objects equals method is false when the content has got changed
indian guyz are still the best in software whatsover from whenever
Durga sir ......Master Blaster.....
Super sir.. it's clearly explained...
I wish i only had watched this video before my lately bad job interview
Did u get these questions?
Nice Explanation sir.
Thank you very much sir for an excellent explanation.
Wouldn't the two strings refer to the same object as that would be returned from the string pool making the refernces same..
Hello sir,
Thankyou for th very nice explanation just one doubt.
At last you said in String and Collection equals() method compares content so what happens with the other class like Integer where 9 == 9 also returns true and two different Integer object with 9 and 9 also returns true.
Thank you sir, I got point👍
public static void main(String[] args) {
String s1 = "Durga";
String s2 = "Durga" + "Software";
String s3 = s1 + "Software";
System.out.println(s2 == s3);
}
The above code will print false, But if i will make s1 as a final then it will print true. Can someone explain what is the reason behind the scene. :)
Perfect Sir 🔥
Both are true in this example. Please apply string literal pool concept.
He is right. He is creating a new String object with 'new' keyword. so their reference will not be same. if he would use
String a = "string";
String b = "string";
//now the strings a and b taken from pool. and
System.out.println(a == b); // this would print true.
I think writing the next case will make it more clear.
String a = new String("abc");
String b = new String("abc");
// now these reference are not same,
System.out.println(a==b); // this would print false;
Banugoban Kones When you try to create with new keyword. I think it first it will check from the literal pool, if not present in pool then it will create.
Banugoban Kones That's true, but the two cases would be false if the equals() wasn't implemented in the user supplied class
Sidhartha Velaga When new keyword is used, object is not checked in pool, or placed in pool. This page explains clearly..www.journaldev.com/797/what-is-java-string-pool
Amazing
Great
Thank you sir🙂
can u plzz give me any example of refference comparison..i mean in actual programming where we need refference comparison and why?
String s1= new String("obj");
String s2= new String("obj");
System.out.println(s1.equals(s2));//true
System.out.println(s1==s2);//false
Is it fine then in case of StringBuffer and StringBuilder the out put is false false what is the reason sir....
Because of mutable of string buffer and string builder it will override from object class
public class animal {
String name;
animal(String n){
n=name;
}
public static void main(String[]args){
animal a = new animal("dog");
animal b = new animal("dog");
System.out.println(a==b);
System.out.println(a.equals(b));
}
}
I get output in both cases "false".
Where have I made a mistake?
give return type void to string
Nice explanation !
Good Explanation
nice explanation sir.....
Sir you told us about this below case:-
String s3=new String("Jyoti");
String s4=new String("Jyoti");
System.out.println(s3==s4); -------------->false
System.out.println(s3.equals(s4));---------->true
What will happen in this case?
String s1="Jyoti";
String s2="Jyoti";
System.out.println(s1==s2);-------------->true(Why true?)
System.out.println(s1.equals(s2));------------->true
Because, in the other example(String s1="Jyoti"; String s2="Jyoti"; System.out.println(s1==s2);-------------->true(Why true?) System.out.println(s1.equals(s2));------------->true), you are creating the String objects through String literal, which uses the concept of String interning.
In the second case it will give true because when u r declaring String s1 and s2 it is stored in string constant pool. If we are declaring string as in the second case if the content is same means it will have same reference hence s1==s2 will give you true.
Thanks
String s1=new string ("durga ")
String s1= new string ("soft")
Sopln(s1==s2)
In this case the output is true or false... Please explain sir..
this would be false because neither the address nor contents are the same. Regardless of whether you do s1==s2 or s1.equals(s2), it would be false.
In this case u r get true because in ==u only see the address of the object
Thanks a lot sir
thank you so much sir..
God of Java
But then what about Object class equals method ? It is by default reference type comparison !
+Peterolen yeah i understood that after watching his videos on java.lang package
String a=new String("Hello");
String b= new String("Hello");
sop(a.hascode());
sop(b.hascode());
Why is the hascode same ?
Shiva Shankar please have a look at string pool concept once , it will clarify your doubt.
Why c programming == not check reference only content check...
String ss="sff";
if(ss=="sff")//true!
{
System.out.println("sdf");
}
why it is true and entering in ''if'' block
sir great explanation but as i am from north india your accent was quite tough for me to understand
but it was overall a great video
You missed a major point here. You are actually talking about the equals method in the String class. But the fact is, the String class actually overrides the equals method in object class to compare values. The actual implementation of the equals method "in object class is to compare references not values"!
And still if you disagree with me, please run this simple example in your IDE and check it out for yourself:
public class Application {
private int i;
Application(int i) {
this.i = i;
}
public static void main(String[] args) {
Application application = new Application(10);
Application application1 = new Application(10);
String s = new String("10");
String s1 = new String("10");
System.out.println(application.equals(application1));
System.out.println(s.equals(s1));
}
}
Dear Ashwin you are said right watch this video completely. Durga sir told at last of this video. .equals() of object class meant for reference compare, .equals() method of string class is overridden for content compare which is same as you know. Durga sir can not miss anything i believe.
Bro,if equals method in object class is used for reference,then what is the need for hashcode
Wondering if this is a statement or a question. Assuming it is a question koushik m afraid they serve completly different purposes. Two equal objects always have the same hashcode but vice versa may not be always true.
then can you explain me with sample code
two equivalent object are equal by .equal() is its true then compulsory there hashCode must be same.
Thank u sir.
please upload swing and event handling tutorial by durga sir
Hello,
We are very Happy to say Now you can access All DURGA Sir's
Core Java with OCJP/SCJP Video Sessions(200 Videos,21 Chapters,200 hours ). To
get Maximum Benefit from these video sessions, compulsory you have to write
notes also. Sir will dictate each and every point clearly.
Demo Sessions on
RUclips:
1.LanguageFundamentals(16Videos) ruclips.net/video/eTXd89t8ngI/видео.html
2.Operators&Assignments(7Videos) ruclips.net/video/1JGOPhIyhAM/видео.html
3.FlowControl(6Videos) ruclips.net/video/X6rS9vD9qM/видео.html
4.ExceptionHandling(10Videos) ruclips.net/p/PLd3UqWTnYXOnSkaum39zWYI6bPb3i7liz
Please give your valuable feedback and it is very important
and helpful for us.
Note:-If you are interested for full version of videos
please revert back for more information.
Fee : 6000/-
Duration: 6-months
DURGASOFT Online
Training Team,
Mobile : +91-8885 25
26 27, +91-7207 21 24 28
Mail ID : durgasoftonline@gmail.com ,
durgasoftonlinetraining@gmail.com
what kind of notes ? please specify. i am not clear about event handling i need it from scratch level
public boolean equals(Object obj)
{
if (this == obj) return true;
if (obj == null) return false;
if (this.getClass() != obj.getClass()) return false;
Person that = (Person) obj;
if (this.age != that.age) return false;
if (!this.fname.equals(that.fname)) return false;
if (!this.lname.equals(that.lname)) return false;
return true;
}I have a piece of code like above , in that code why we are checking for the inequality of classes [ if (this.getClass() != obj.getClass()) return false;]I mean why should we check for the inequality of classes instead of checking for the equality of classes.and why do we need to check all those things, could u please explain me a little bit In detail.Thanks in advance.
s1==s2 is true right? because strings are stored in strong pool and s1 and s2 same object right?
Yes
Anna nuv thop....
Even for Indians..
How to know the references are having same object or not.
use this ==
Sir can you give me advance video link... plz sir
Tnq sir
int a=5;
int b=5;
a== b is giving true, here its checking content or reference....
String a="xxx";
String b="xxx";
a==b is giving true only,when string is created through object that time only false....why this....???
siva muthu Because there is a DIFFERENCE between "int" and "String".
"int" is a primitive datatype, whereas in Java, "String" is a CLASS, and not a datatype like "int" or "char".
So the context of " == " operator changes depending on how and where you are using it.
Let's take your example, first case:
int a = 5; int b = 5;
S.o.p(a == b); //true
Here what is happening is the == operator acts as a "EQUALITY" operator because the "context" in which it is being used, i.e. CHECKING FOR EQUALITY between 2 PRIMITIVE DATATYPES.
Note that " == " can also be used on other primitive datatypes, like byte, long, float, char, double as well to check their relation/or to compare them.
Now, second case:
String p = "xxx"; String q = "xxx";
S.o.p(p == q); //false
Here what is happening is first of all you are creating TWO SEPARATE INSTANCES of a String(i.e. a Class).
Therefore in doing so, you are assigning TWO SEPARATE MEMORY LOCATIONS for them.
So when you use " == " operator or basically -- "EQUALITY" in the context of TWO SEPARATE OBJECTS, what you are doing is checking if TWO SEPARATE OBJECTS ARE SAME OR NOT. Which they obviously are not because they are, as we declared -- SEPARATE.
In technical terms, you are checking whether "p" & "q" point or have the SAME MEMORY LOCATION or not.
Which they obviously don't because they are two separate entities/instances/objects.
So to overcome this problem in the context of "object equality", we have the method *.**_equals_**();* You can check the source code of the String.equals() method to understand how it is checked whether the "content" of two Strings is the same or not.
Hope that helped clear the doubt! :)
siva muthu Here is another example you can understand much better at how == operator works:
int a = 5;
int b = 5;
Integer p = new Integer(a); // i.e. numeric value stored in p will be that of int a, i.e. 5
Integer q = new Integer(b); // i.e. numeric value stored in p will be that of int b, i.e. 5
S.o.pln(a == b); // true, coz same values.
S.o.pln(p == q); // false, coz two different objects.
S.o.pln(p.equals(q)); // true, coz same content.
S.o.pln(p.intValue() == q.intValue()); // true, coz same numeric values stored in both.
S.o.pln(p.compareTo(q)); // 0, read below.
_In above statement, *0 means numeric comparison result of p & q is true*,
*-1 means p is less than q* or basically whatever the argument was passed,
*1 means p is greater than q* or basically whatever the argument was passed._
Now you see the difference between context of " == " operator between a "primitive datatype" and an instance of a Class? :)
Here is one thing you should keep in mind -
now as per according to your ques both s1 and s2 are now in same memory called as String Pool.
Note-All String stored in same memory called "String Pool " but except if you use "new" keyword (like in s1 and s2 ) eg-
String s1=new String("hi");
String s2=new String("hi");
String s3="hi";
String s4="hi";
Now both s1,s2 are stored in heap memory that is s1 pointing to one object and s2 pointing to another different object (stored in heap), so content is same but the reference is different but s3 and s4 are stored in the string pool.
Hence , s3 and s4 pointing to same memory that is String pool and has same content "durga" so as a result == and .equals(), both will check same content, Give output as true (but not in the case of new (that is in heap memory)).
Hope you got this keep learning.
explain the last note part in details please
great explanation
Wt abt this String s="durga";
String s1=new String ("durga");
s==s1
Obviously false.. because your first string object is created in pool string memory and second string object is created is heap memory
s1 referring to the object in heap memory but s referring to the object in String Constant Pool memory in memory area
"double equal operator mendirfdirf difference comparison"
please upload collection map videos
String str1 = new String("java");
String str2 = new String(str1);
S.o.pln(str1==str2)
Still false as str2 points towards str1???please help here
S.o.pln(str1.equals(str2)); true
You are creating two separate String objects. So, str1 == str2 is false.
String str2 = new String(str1) means String str2 = new String("java").
You are only passing the value of the str1 object in the str2 object's constructor. It doesn't mean you are referencing to str1 object. When you use 'new' keyword, a new object is created. So, if you want to reference str1 object then do like this:
String str2 = str1; Do not use 'new' with str2. If you do so, a new object will be created on str2 will point to this.
Meanta for ref comparison
And what's about if(int i=7==int j=7)
System.out.println(i=7)==(j=7)); is the actual format i==j show true (bcz == ment for reference comparison )
wow
String s1="Durga";
String s2="Durga";
s1==s2//true
s1.equals(s2);//true
In this case both returns true why?
When we are creating a string using equals operator. Jvm checks the string pool whether the string is already present. If it's not present create a new object, If it's present it simply creates a reference and point to already existing object, with out creating a new one. In your example
String s1 = "Durga"
Jvm checks the string pool since the object is not present. It creates object durga and a reference s1 and points s1 to durga
String s2 = "Durga"
JVM checks the string pool since the object Durga already present. It only creates a reference s2 and points to the object.
Now the single object Durga is pointed by both s1 and s2
Since == stands for reference comparison and both s1 and s2 are Reffering to the same object the result will be true
what if i write like this.
String s1 = "durga";
String s2="durga";
System.out.println(s1==s2);
System.out.println(s1.equals(s2));
****************************************************************************
****************************************************************************
Now both the results are true . Then what is the difference between the == operator and .equals() method.Sir , We cannot explain like what you said. Then, interviewer may cross question like asking such question.
output will be true....😉for explaination pls read string pool concept.
String s1n s2 points to the same object as content of both String is same
so both == and .equals() will give true
Here is one thing you should keep in mind -
now as per according to your ques both s1 and s2 are now in same memory called as String Pool.
Note-All String stored in same memory called "String Pool " but except if you use "new" keyword (like in s1 and s2 ) eg-
String s1=new String("hi");
String s2=new String("hi");
String s3="hi";
String s4="hi";
Now both s1,s2 are stored in heap memory that is s1 pointing to one object and s2 pointing to another different object (stored in heap), so content is same but the reference is different but s3 and s4 are stored in the string pool.
Hence , s3 and s4 pointing to same memory that is String pool and has same content "durga" so as a result == and .equals(), both will check same content, Give output as true (but not in the case of new (that is in heap memory)).
Hope you got this keep learning.
Hey Arjun, I have a stupid doubt.
As you said, since s3 and s4 points to same memory i.e. Stringpool it returns true. But what if
String s3="hi";
String s4="hiArjun";
s3 == s4 returns false. Why? Both should be present in Stringpool in a same memory. It should have returned true as well!
Can you kindly explain?
@shreyam
String s3="hi";
String s4="hiArjun";
As string is immutable, as soon as you make any change in the string, it will make a new object in string pool. That means the reference will change as soon as you change the content.
Hmn
I didn’t understand more than half of the words.
Then find another video.