.equals() vs. == in Java - The Real Difference
Вставка
- Опубліковано 28 вер 2024
- 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...
so far I've watched several videos with the same topic but this video only explained well. Thanks man!
Awesome! Very glad I was able to help!
Agreed
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!
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.
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
Really fascinated at how good you are able to explain. Thanks for the great video!
John, this was an amazing tutorial!
I had a query though; on the objects, do we override the equals() or is it inferred?
we override it
6:15
Small piece of feedback: title shoulda been ".equals() and == are not equal"
Thanks for the great video!
.equals() != ==
@@CodingWithJohn even better!
OMFG please keep your content comming...im having a blast learning from you man. Im deeply grateful for all your lessons.
Thanks Johnny Sins
Please be polite with your words👍
@@lyrixvibzhe said thank you
@@1blkvincido you know Johnny sins?💀
@@1blkvinciThat's not the right way to say thank you.
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 🙂
Love the Kramer picture in the back, my grandpa has one just like it! Thanks for the amazing videos!
Might also be worth mentioning that you can use == with enum's as well.
Ah Lord! can't just say how easy you explained it. I have been really confused for several days about this simple .equals in object class and now I know how java processes it. Thank you so much for this video. Subscribed liked and commented. Keep up with your good work!!!!
By the beard of Zeus! Your contributions to the world of programming are nothing short of epic. Your Java beginner's playlist is truly a stroke of genius, and I speak for many when I say, you are the real MVP!
Wow, noob here, didnt know those details till you explain it, massive thanks John!
the last part was really good!
tus videos tienen un gran valor, muchas gracias por compartir tu conocimiento
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?.
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
This is awesome! Can you do a video on priority queues and comparators, and how they come together?
lmao, that head pop up at the beginning cracks me up!
Thanks. Useful, however you still did not cover how to compare 2 objects on the Dog example staring from 05:08
What’s the codes for .equals() in class Dog?
I don't do Java, but what about enumerations? If they exist does the == work?
Yes, for enums you also use ==
String Pool, the place where are inline strings are saved, that's why you use new String("hello")
I wish you were my lecturer at Uni. You have talent man!
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 ❤
Thanks John, your tutorials are very helpful. You are a great teacher, hats off!
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??
Amazing explanation. My Uni java lecturer even didn't taught us this important concept. Keep up the great job!
Very clear. Awesome examples and also my eyes love the dark theme ^^
This channel is very very good.
Good explanation! What about enum comparation? What should I use?
Thanks John, your tutorials are awesome.
Thank you so much, your videos are pretty helpful 😊
It seems I've found my coding channel. Thanks for the video :)
Thx for your clear presentation Sir
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?
I think better you recheck 1st case, it has to be true
Thanks John!
To the point explanation
Great video as always. Thank you for your dedication!
Did he ever make that video on how to write a good equal method for your class?
Thank you so much.. Your explanation is very clear...!!!
Thanks! Your videos are great!
Hi~ What's your coding software? looks very pretty.😀
== is relevant to compare enums, too
Perfect concept
And what with Enum ?
How to input a single character directly? (without waiting for user to press enter key) in Java.
Great lessons as usual. Thanks.
It all boils down to the fact that strings are immutable right?
I love your videos, thank you
thanks
This is a very useful video.
So it's basically like pointers in c++? got it.
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.
Amazing tutorial!
hi what about using the == operator with text, will it be if(i=="john")or single quotes or would it be (if i.equals??)
Really Really cool!
Thank you john!!
dude, your videos are amazing
I am going through you video and its very easy to understand . One more request can you please provide session for Stack vs heap memory.
Hello John, after You Ctrl + click on .equals (4:15 min) how did you go back? I mean how to hide all that info that appeared after Ctrl + clicking?
It just opens the file where .equals is defined, just close this file
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.
Man they rejected me yesterday based on this question
welllllll
== is fine for enums
This is a gotcha for those coming from C#. Great explanation John!
wow wait im confused....
you wrote String string1 = new String ("hello");
Could you not have just wrote
String string1 = "hello"; ??
please read sth about the String Pool
is the word string pronounced SHtring in English?
Hmm interesting video you are posting
john are using Eclipse
In this one yes, but in more recent videos I've switched to IntelliJ since I found that most viewers use that.
@@CodingWithJohn i am practicing in eclipse i have a problem in Eclipse i don't know how to remove the file from the Create a new file resource. i have five files their empty and only one has data how to remove them??
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.
nice one John :)
Goldmine
Sidenote: You can also == Enums in Java, you forgot to mention that
love u
Johnny Sins star of adult star is (.equals) john the star of programming world /*for me at least i guess*/.
Why do you say "equals" instead of "gets" when assigning variables
Because the '=' character in general represents the idea of equality. If you put code into english, it's only natural to translate it as "equals". For most programming languages though that character stands for the assignment operator - which deals with a somewhat related topic.
@@rufusneumann9703 i dont know if you are relatively new to programming or not but the correct way to say "=" is "GETS" not equals. "==" is pronounced "equals". "=" is merely the character thats used to represent assignment and has no link to its algebraic meaning. Think about it this way, "x = 5" is not the same as "5 = x". You arent stating that the memory location x is equal to 5, but rather it GETS 5.
@@niccster1061 Interesting claim from you that his should be the CORRECT way to pronounce. Never heard it in my life.
@@rufusneumann9703 i mean it makes alot more logical sense than saying "equals" and its also much shorter
String store string pool if same value then memory location how it will show false when we compare ??????
bro why you look like johnny sins
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.❤
Simple and easy to understand. Thank you!
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.
go away bootcamp people
That was incredibly well explained! Thanks a lot!
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! :)
😂😂
Hey pls make video on comparable comparator interface in java
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.
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
@@lumschente Don't know if it is true, but that makes sense
I was thinking about the same, @john could you please clarify this question
Here is the other video of your we were referring to 🙂
ua-cam.com/video/Bj9Mx_Lx3q4/v-deo.html
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
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!
Superb sir❤
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!".
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 ?
Can you do a video sometime on instanceof, thank you.
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 :)
John, please clarify this for me, in text, how would you declare and compare 2 string objects for equality?
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.
Strings might be equals using == operator if Java had operator's overloading like C++ has.
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
Why the equals method inside Dog class take an Object type parameter instead of a Dog type parameter?
holy shit that was an awesome explanation!!!!!!! what a goat!
What about StringBuilder & StringBuffer ??
String word = "something";
is primitive type
but still can use .equal() like it was an object 😂