.equals() vs. == in Java - The Real Difference

  Рет қаралды 188,992

Coding with John

Coding with John

Күн бұрын

Complete Java course: codingwithjohn...
Watch now to learn the difference between ".equals()" vs. "==" in Java. Full tutorial on the difference between "==" (double equals) and the ".equals()" method in Java. Especially for Strings, when do you use ==, and when do you use .equals?
Simple equality checks in Java can be tricky, but the facts are simpler than you may think.
This is a very beginner friendly beginner's Java coding lesson tutorial, where we'll discuss the difference between == and .equals() when doing equals checks in Java.
Learn or improve your Java by watching it being coded live!
Hey, I'm John! I'm a Lead Java Software Engineer who has been in the industry for more than a decade. I love sharing what I've learned over the years in a way that's understandable for all levels of Java developers.
Let me know what else you'd like to see!
Links to any stuff in this description are affiliate links, so if you buy a product through those links I may earn a small commission.
📕 THE best book to learn Java, Effective Java by Joshua Bloch
amzn.to/36AfdUu
📕 One of my favorite programming books, Clean Code by Robert Martin
amzn.to/3GTPVhf
🎧 Or get the audio version of Clean Code for FREE here with an Audible free trial
www.audibletria...
🖥️Standing desk brand I use for recording (get a code for $30 off through this link!)
bit.ly/3QPNGko
📹Phone I use for recording:
amzn.to/3HepYJu
🎙️Microphone I use (classy, I know):
amzn.to/3AYGdbz
Donate with PayPal (Thank you so much!)
www.paypal.com...
☕Complete Java course:
codingwithjohn...
codingwithjohn...

Пікірлер: 252
@rykageee
@rykageee 3 жыл бұрын
so far I've watched several videos with the same topic but this video only explained well. Thanks man!
@CodingWithJohn
@CodingWithJohn 3 жыл бұрын
Awesome! Very glad I was able to help!
@phillipmiller4642
@phillipmiller4642 3 ай бұрын
Agreed
@DanielOliveira-ru7mt
@DanielOliveira-ru7mt Жыл бұрын
Thanks Johnny Sins
@lyrixvibz
@lyrixvibz 3 ай бұрын
Please be polite with your words👍
@1blkvinci
@1blkvinci 2 ай бұрын
@@lyrixvibzhe said thank you
@lyrixvibz
@lyrixvibz 2 ай бұрын
@@1blkvincido you know Johnny sins?💀
@SifatUllah-12
@SifatUllah-12 Ай бұрын
​@@1blkvinciThat's not the right way to say thank you.
@Daresigmally
@Daresigmally Жыл бұрын
Oh my god I'm genuinely so thankful I discovered this Channel, John explains stuff like no one else does, you just earned yourself a subscriber mate, thank you for all the efforts.❤
@praveens9233
@praveens9233 Жыл бұрын
Warning ⚠️ : If you are going to override .equals method,you have to override your hascode method. Otherwise there will be a mess with those objects whenever you hashing
@dhavewala
@dhavewala 2 жыл бұрын
John, this was an amazing tutorial! I had a query though; on the objects, do we override the equals() or is it inferred?
@wiktorstankiewicz3568
@wiktorstankiewicz3568 2 жыл бұрын
we override it
@fullfungo
@fullfungo 2 жыл бұрын
6:15
@Visionist
@Visionist 3 жыл бұрын
Simple and easy to understand. Thank you!
@magicalhats
@magicalhats 2 жыл бұрын
I'm a newbie dev and I finished a bootcamp but your videos topics are all the topics I found confusing during class and always wondered about. TY so much.
@alexanderpanday
@alexanderpanday 4 ай бұрын
go away bootcamp people
@brunomartel4639
@brunomartel4639 11 ай бұрын
is it too bad if we declare Strings as literal all the time? like String string1= "hello" instead a declaring an object with it? I mean is there a reason to declare an object String?.
@radhemohannaamhai
@radhemohannaamhai 2 жыл бұрын
Man they rejected me yesterday based on this question
@brtkgromek
@brtkgromek 2 жыл бұрын
I'm glad I've found this chanel. I've never been more educated by any other escaped convict in my entire life! Keep it up! :)
@enigma6463
@enigma6463 2 жыл бұрын
😂😂
@Amy-zb4iq
@Amy-zb4iq 2 жыл бұрын
What’s the codes for .equals() in class Dog?
@streamity24
@streamity24 2 жыл бұрын
Really fascinated at how good you are able to explain. Thanks for the great video!
@binilgeorge7358
@binilgeorge7358 2 жыл бұрын
But in your strings are immutable video, you said when initializing a string variable java points it to a pre existing string memory address. With that, here hello is already exist when you initialize the second string. Therefore both variable should point to same address, that is using == returns true. ? I am confused plz answer me.
@lumschente
@lumschente 2 жыл бұрын
the string itself is probably wrapped in a class and the class stores the reference to the string pool but the objects are initialized in different memory regions
@binilgeorge7358
@binilgeorge7358 2 жыл бұрын
@@lumschente Don't know if it is true, but that makes sense
@shravanbandari
@shravanbandari 2 жыл бұрын
I was thinking about the same, @john could you please clarify this question Here is the other video of your we were referring to 🙂 kzbin.info/www/bejne/eJucfquVgd1mp5Y
@InfoBuzz1130
@InfoBuzz1130 Жыл бұрын
Hey pls make video on comparable comparator interface in java
@ovey2214
@ovey2214 2 жыл бұрын
That was incredibly well explained! Thanks a lot!
@micahrufsvold
@micahrufsvold 2 жыл бұрын
Small piece of feedback: title shoulda been ".equals() and == are not equal" Thanks for the great video!
@CodingWithJohn
@CodingWithJohn 2 жыл бұрын
.equals() != ==
@micahrufsvold
@micahrufsvold 2 жыл бұрын
@@CodingWithJohn even better!
@GenjaOrigins
@GenjaOrigins 2 жыл бұрын
You are great. Congrats for channel and being Team Leader. Maybe you could/should make a video talking about what should a junior know. I think i know equals now, exceptions/throw/finally/catch etc, im learning generics and i undertand but i saw a generic method in an interview(company was about HR, and i was asked 4 Design Patterns which i knew but wasnt good enough for company anyway) i had no idea what it was even if i knew generics it was kind of pro code/ultra weird and hard i think it was with lists btw..i also hate leetcode i prefer videos like yours to actually learn java. I would also learn more from you cause you good and you enjoyable i hope you do the same in your job irl. i think i also know most of collections hashmap/set etc
@cjm101
@cjm101 Жыл бұрын
Feeling lucky to have found this channel, I've been self studying on and off for a couple years and I'm pretty sure I should have known these key concepts by now, sincere thanks for these clear and understandable teachings!
@dotanon
@dotanon Жыл бұрын
I got back into Java recently after not using it for like 8 years and have been haphazardly using == for strings and it has been working, presumably because I have been always using strings as state variables in games, and so have been manually typing the strings in my conditions as literals (if (facing == "up")) etc. I saw a comment on another video and I'm glad I found this early enough to refactor everything. haha.
@olivierbegassat851
@olivierbegassat851 Жыл бұрын
These are beautiful videos man 😁 Every sentence of yours resolves an issue I had and leads to the next question I had. So helpful ! Thanks 🙂
@danielcommins1285
@danielcommins1285 2 жыл бұрын
John, where did you get the source and how did you attach the source to the binaries? UPDATE: solution is to point your JRE path to the path with the JDK instead!
@cryptoInNutshellR
@cryptoInNutshellR Жыл бұрын
Thanks. Useful, however you still did not cover how to compare 2 objects on the Dog example staring from 05:08
@MasonJF
@MasonJF 2 жыл бұрын
See this is interesting, because I thought with Javas memory management scheme that it uses and forces strings to be immutable would reference the same object in memory, even though the variables are two seperate ones. Eg. I was under the impression that String string1 = "James"; String string2 = "James"; these would both point to the same object in memory because these are the same value, which you would think would cause the == operator to go "Oh hey, this is true!".
@manojkarthik6158
@manojkarthik6158 3 ай бұрын
Question Integer a = 100; Integer b = 100; System.out .println( a==b ) The output is true Integer a = 200; Integer b = 200; System.out .println( a==b ) The output is false Why ?
@BEN-ys6gu
@BEN-ys6gu 2 жыл бұрын
I don't do Java, but what about enumerations? If they exist does the == work?
@LichtHund
@LichtHund 2 жыл бұрын
Yes, for enums you also use ==
@Jamiered18
@Jamiered18 2 жыл бұрын
Honestly I think Java got this wrong. Other languages, like C# and Python use `is` to check referential equality, whereas `==` can be overridden, just like `.equals()` can. Much more concise and suitable to actual common use.
@iamnotfamous6591
@iamnotfamous6591 5 ай бұрын
but in one video you said that java make different variables but when we store same values to it java make them point to the same locations where the value is stored!!! why??
@pawehericht2673
@pawehericht2673 3 ай бұрын
at 1:46 it is worth saying, that String one = "1"; String oneBis = "1"; when comparing one == oneBis will output true? what has changed and why String one = new String("1) gives us false when ==? The answer is: The String pool I believe
@iyhan1987
@iyhan1987 2 жыл бұрын
7:03 I guess almost everyone(who studies Java seriously) knows about the pool of strings cause it is a pretty common topic. I bet if you want really “to impress some nerds” you should show them some “pool of Integer” style tricks :)
@galirams9653
@galirams9653 4 ай бұрын
John, please clarify this for me, in text, how would you declare and compare 2 string objects for equality?
@paulhetherington3854
@paulhetherington3854 Жыл бұрын
.equal? It breaks up? False f(x) < U.S. or English measure - Ei Pirate Co. Double scales
@wojtekzajaczkowski280
@wojtekzajaczkowski280 Жыл бұрын
String word = "something"; is primitive type but still can use .equal() like it was an object 😂
@yuriytheone
@yuriytheone Жыл бұрын
Strings might be equals using == operator if Java had operator's overloading like C++ has.
@Zalaniar
@Zalaniar Жыл бұрын
I was gonna say something about the weird use of a string constructor at the beginning, but it's a good thing I decided to wait, lol. IIRC, the javadoc even yells at people about wanting to use == for strings which I find hilarious.
@iruga7379
@iruga7379 2 жыл бұрын
OMFG please keep your content comming...im having a blast learning from you man. Im deeply grateful for all your lessons.
@Daryl482
@Daryl482 Жыл бұрын
Hi~ What's your coding software? looks very pretty.😀
@matteoZattera
@matteoZattera 2 жыл бұрын
Why the equals method inside Dog class take an Object type parameter instead of a Dog type parameter?
@jesusromero71
@jesusromero71 2 жыл бұрын
tus videos tienen un gran valor, muchas gracias por compartir tu conocimiento
@akna1987
@akna1987 7 ай бұрын
These videos are great! But you should have included a video on how to implement the .equals-method and compare-to method to your own class
@bhukyasharath2015
@bhukyasharath2015 Жыл бұрын
Superb sir❤
@bucztechph
@bucztechph Жыл бұрын
No wonder why it won't work on string, glad i quit c++ and find a better language that has good methods for string
@amruthashekar3544
@amruthashekar3544 2 ай бұрын
Hello John, please answer why i am getting false in first case? String str1 = new String("hello"); String str2 = new String("hello"); System.out.println(str1.equals(str2)); and String str = new String("java"); String rev = new String("avaj"); System.out.println(str.equals(rev)); how string comparision is done, is it character by character?
@SupunWithana-t8x
@SupunWithana-t8x Ай бұрын
I think better you recheck 1st case, it has to be true
@surkesden
@surkesden 2 жыл бұрын
Good explanation! What about enum comparation? What should I use?
@raygilbertflies
@raygilbertflies Жыл бұрын
But, but.... This works. String string1 = "hello"; String string2 = "hello"; if (string1 == string2) { System.out.println("The strings are equal"); } else { System.out.println("The strings are not equal"); }
@CodingWithJohn
@CodingWithJohn Жыл бұрын
Here's why, it has to do with how string literals are handled: kzbin.info/www/bejne/eJucfquVgd1mp5Y
@raygilbertflies
@raygilbertflies Жыл бұрын
@@CodingWithJohn Thanks John. And that's why I subscribed. :)
@HackInTheBoxx
@HackInTheBoxx 2 жыл бұрын
Can you do a video sometime on instanceof, thank you.
@InfiniteWisdom1.0
@InfiniteWisdom1.0 9 ай бұрын
Thank you so much, your videos are pretty helpful 😊
@unknownzodiac9134
@unknownzodiac9134 Жыл бұрын
Did he ever make that video on how to write a good equal method for your class?
@manishvashishth2663
@manishvashishth2663 2 жыл бұрын
What about StringBuilder & StringBuffer ??
@Dean-rs2nt
@Dean-rs2nt 3 ай бұрын
wow wait im confused.... you wrote String string1 = new String ("hello"); Could you not have just wrote String string1 = "hello"; ??
@pawehericht2673
@pawehericht2673 3 ай бұрын
please read sth about the String Pool
@scottcarter4526
@scottcarter4526 Жыл бұрын
Might also be worth mentioning that you can use == with enum's as well.
@SupunWithana-t8x
@SupunWithana-t8x Ай бұрын
how to override equals() in Dog class???
@Programming-for-all-u2l
@Programming-for-all-u2l 2 жыл бұрын
I wish I could find the complete video of java.
@akinyeleoluwafemi7007
@akinyeleoluwafemi7007 2 жыл бұрын
It all boils down to the fact that strings are immutable right?
@bextrekks8354
@bextrekks8354 2 жыл бұрын
lmao, that head pop up at the beginning cracks me up!
@Eduardado
@Eduardado 2 жыл бұрын
Very clear. Awesome examples and also my eyes love the dark theme ^^
@technoultimategaming2999
@technoultimategaming2999 2 жыл бұрын
And it's very intuitive why == cannot always work. If you have a Room class and you ask java to check if a room is equals to another room... Well... It doesn't know what to check, should it check dimensions of the room, should it check furniture inside? While with numbers it's very obvious what people mean when one number equals another, but for objects like rooms it's really up to the programer to define what "equals" actually means
@aaronmaiden3606
@aaronmaiden3606 Жыл бұрын
Could this be the equals() reimplementation in Dog class? public boolean equals(Object obj){ return this.name.equals(obj.name) && this.age == obj.age; }
@alexal8088
@alexal8088 11 ай бұрын
is the word string pronounced SHtring in English?
@aureliasam2092
@aureliasam2092 2 жыл бұрын
Hi John you did very well in this lesson. I tried to learn .equals and == from a professor but I couldn't understand it and now I got the point from you in 5 minutes.
@syedmujtaba727
@syedmujtaba727 2 жыл бұрын
holy shit that was an awesome explanation!!!!!!! what a goat!
@srin_meow
@srin_meow 2 жыл бұрын
i though you were gonna say hey! vsauce
@Loghinesko
@Loghinesko Жыл бұрын
The "new" keyword means that when we use it to create an instance of a class, we tell the computer that we want to allocate memory space to put the new object in.... After that, we want to create a new object again in the class, so we need to use the "new" keyword again which again tells the computer that we want to allocate memory for the new object, so it allocates a new memory address to the new object. Right now, we have the 2 objects, but they have different memory addresses because they were instantiated in different memory areas. When we compare objects, we are actually comparing the memory addresses of variables (objects). In fact, these variables are pointers to objects.
@ivanzq21
@ivanzq21 Жыл бұрын
what does mean new=String mean?
@konstantinzakharov5643
@konstantinzakharov5643 Жыл бұрын
I love this guy! I am hitting the Like button!
@ernestoc.d.1868
@ernestoc.d.1868 3 жыл бұрын
I would like to see the "How to implement a good .equals() method".
@inx1819
@inx1819 2 жыл бұрын
Step 1. Use Lombok
@wannabeserpento99
@wannabeserpento99 2 жыл бұрын
Eclipse can generate one for you and I don't know why he doesn't mention it
@Pacvalham
@Pacvalham 2 жыл бұрын
1. check for identity (if(this == obj) return true;) 2. check for type (if(!(obj instanceof _ThisClass_ )) return false;) 3.a cast the object ( _ThisClass_ castObj = ( _ThisClass_ ) obj;) 3.b compare each field (return this.a == _[or .equals()]_ castObj.a && this.b == _[or .equals()]_ castObj.b && ...;)
@thegloriousgoldeneagle
@thegloriousgoldeneagle 8 ай бұрын
I love your videos, thank you
@loop8836
@loop8836 2 жыл бұрын
So Java is loosely typed static language
@shama-_-
@shama-_- Жыл бұрын
thanks a lot you help me to understand the concepts
@colonelh.s.l.3834
@colonelh.s.l.3834 Жыл бұрын
This is awesome! Can you do a video on priority queues and comparators, and how they come together?
@anjelomanoranjan
@anjelomanoranjan Жыл бұрын
Thanks! Your videos are great!
@thwKobas
@thwKobas 2 жыл бұрын
I don't like how you explained part with primitives and objects using == operator. Better explanations would be that == actually does what it need's to do, and not what you expect. True primitive type in background is just that some value INT, or BOOL or whatever, but when you use object and NEW keyword, you are actually comparing not objects but their references (pointers) and ofc those are not equal because you are comparing 2 totally different objects that, so it happens, contain same value, but are still 2 different objects located somewhere in memory, each on it's own. if you use 2 different variables and refer to same object, == will return true because they both reference same memory address of given object. Also you can look at this from different angle as well, .equal is there to compare values of a given object in a way you declare it to be, for example User with name, age, address could be same to another user only if all of those properties are equal, but some object, let say, Hash with property id, and some other properties we don't care can be equal to any other Hash if we just use id for comparison.
@lamaspacos
@lamaspacos 6 ай бұрын
This channel is very very good.
@dhawalparmar7117
@dhawalparmar7117 2 жыл бұрын
Hmm interesting video you are posting
@KorhalKk
@KorhalKk Жыл бұрын
Hey John, I have a relevant question: Im using a Professor p = new Professor ("", 0, 0); and a if(p.getName() == "") and it works, is the getter subverting the logic?
@dotanon
@dotanon Жыл бұрын
You're constructing the instance of the Professor object, but presumably the "" you're passing in as an argument is technically a literal, vs doing something insane like "Professor p = new Professor (new String (""), 0, 0); That would be my guess. So in all likelihood it isn't so much that the getter is subverting the logic, it's more so that the string is a literal and not a new instance of String. I've been doing similar stuff after years of javascript, so my takeaway is always use .equals to be sure you're comparing the value and not the reference just in case. lol. I definitely have a lot of refactoring to do.
@CodingWithJohn
@CodingWithJohn Жыл бұрын
This is correct! When you use string literals Java uses a string pool to share objects among the program to save memory. So they're going to have the same memory address and thus will == each other
@9891254408
@9891254408 2 жыл бұрын
This is the best i have understoon so far...
@pichulio
@pichulio Жыл бұрын
wheeeeeerree is the how to make a good equals video
@lsh_
@lsh_ 2 жыл бұрын
But if you declare a string like this: String s = "hello"; and not like this: String s = new String("hello"); it will just work fine.
@GayAnnabeth
@GayAnnabeth 2 жыл бұрын
welllllll == is fine for enums
@Sui-Zan
@Sui-Zan 2 жыл бұрын
Orange is the new black, John. You look great! Thank you very much for the videos. You make java seem so simple to me.
@larakrs15
@larakrs15 Жыл бұрын
hi what about using the == operator with text, will it be if(i=="john")or single quotes or would it be (if i.equals??)
@mehdibash
@mehdibash Жыл бұрын
== is relevant to compare enums, too
@pawewodarczyk1546
@pawewodarczyk1546 Жыл бұрын
You forgot to mention that enums can also be safely compared by == operator ;)
@CodingWithJohn
@CodingWithJohn Жыл бұрын
True!
@tonnytrumpet734
@tonnytrumpet734 3 ай бұрын
Sir I have been watching your videos for around 30 hours last 3 days, thank you so much this is great content I am starting to actually understand Java and see how things from different videos relate to each other, sometimes I can guess what you are going into with your train of thoughts, very well put together videos.
@harlockgaming1476
@harlockgaming1476 9 ай бұрын
Love the Kramer picture in the back, my grandpa has one just like it! Thanks for the amazing videos!
@elijahasefa389
@elijahasefa389 2 жыл бұрын
this channel always dropping gems. Respect.
@meerapatel1116
@meerapatel1116 Жыл бұрын
Is there a video on how to write a code for counting repitatative character? Input : aaabbcc output: 3a2b2c Thanks
@barneylaurance1865
@barneylaurance1865 2 жыл бұрын
I would call `==` the identity operator. It tells us if the two things are identical, not just if they are equal. In the real world two mass produced objects, like two coffee cups might be equal in every aspect you can measure, but they are not identical because they are two distinct objects.
@nilou-s8l
@nilou-s8l Жыл бұрын
You explained sth in 8minutes that my French prof couldn’t explain in 2 hours and made me hate Java for no reason . Thank you ❤
@Zalaniar
@Zalaniar Жыл бұрын
In case anyone is worried about java doubling up on references to strings like that causing weird bugs, don't worry... because strings are immutable, if you try to change one, java will just make a new String object and point the variable to that one instead, leaving the first untouched.
@jeffreydwightryanriley8308
@jeffreydwightryanriley8308 2 жыл бұрын
Is variable type even necessary? That’s why I like php. The types can be manipulated in the database and queries are objects. It allows synthetic interaction essentially in that the programmer ultimately codes states versus implicit phases of data. Such as arrays of arrays.
@kilian9758
@kilian9758 10 ай бұрын
Your tutorials are awesome! Though I wonder if this affects switch cases too. Can I always use switch cases or do I need to be cautious just like with the == operator?
@hba6018
@hba6018 2 жыл бұрын
String Pool, the place where are inline strings are saved, that's why you use new String("hello")
@ruzi173
@ruzi173 Жыл бұрын
This is just the best explanation..wow👏Thank you for all your videos🙏
@vibhorkumar2673
@vibhorkumar2673 2 жыл бұрын
How to input a single character directly? (without waiting for user to press enter key) in Java.
@SecretFols
@SecretFols Жыл бұрын
The underline is even if the primitive or non primitive or user defined type java will check for the memory location and not the values.. (if the values are same then uses same memory location).
@alyankhan806
@alyankhan806 Жыл бұрын
The API contract also states that if you override equals() then you must override the hashcode(), it's an important detail!
@DatCrossGuy
@DatCrossGuy Жыл бұрын
Thanks so much for the video. Genuinely looking forward to the "how to write a good equals method" vid!
@Fawstah
@Fawstah Жыл бұрын
This actually helped me understand why some of the code I was writing was initially breaking. Ty!
@vasimmalekbecomp7065
@vasimmalekbecomp7065 2 жыл бұрын
Johnny Sins star of adult star is (.equals) john the star of programming world /*for me at least i guess*/.
@cananozdemir8913
@cananozdemir8913 8 ай бұрын
I just bought his full Java course. Amazing explanation .
Array vs. ArrayList in Java Tutorial - What's The Difference?
17:36
Coding with John
Рет қаралды 530 М.
GIANT Gummy Worm Pt.6 #shorts
00:46
Mr DegrEE
Рет қаралды 102 МЛН
An Unknown Ending💪
00:49
ISSEI / いっせい
Рет қаралды 57 МЛН
Spongebob ate Patrick 😱 #meme #spongebob #gmod
00:15
Mr. LoLo
Рет қаралды 19 МЛН
Naming Things in Code
7:25
CodeAesthetic
Рет қаралды 2,1 МЛН
Lambda Expressions in Java - Full Simple Tutorial
13:05
Coding with John
Рет қаралды 746 М.
Java String Comparison Tutorial (Equals vs == in Java)
6:45
Alex Lee
Рет қаралды 89 М.
Exception Handling in Java Tutorial
13:20
Coding with John
Рет қаралды 391 М.
02. Equals and HashCode Contract & Different Variations
11:19
Ankit Wasankar
Рет қаралды 58 М.
Generics In Java - Full Simple Tutorial
17:34
Coding with John
Рет қаралды 1,1 МЛН
#58 Object Class equals toString hashcode in Java
12:00
Telusko
Рет қаралды 113 М.
God-Tier Developer Roadmap
16:42
Fireship
Рет қаралды 7 МЛН
Why I’m Switching To Go in 2024
8:10
Awesome
Рет қаралды 65 М.