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

КОМЕНТАРІ • 252

  • @rykageee
    @rykageee 3 роки тому +143

    so far I've watched several videos with the same topic but this video only explained well. Thanks man!

  • @cjm101
    @cjm101 Рік тому +4

    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 Рік тому +2

    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.

  • @praveens9233
    @praveens9233 Рік тому +18

    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

  • @streamity24
    @streamity24 2 роки тому +6

    Really fascinated at how good you are able to explain. Thanks for the great video!

  • @dhavewala
    @dhavewala 2 роки тому +20

    John, this was an amazing tutorial!
    I had a query though; on the objects, do we override the equals() or is it inferred?

  • @micahrufsvold
    @micahrufsvold 2 роки тому +2

    Small piece of feedback: title shoulda been ".equals() and == are not equal"
    Thanks for the great video!

  • @iruga7379
    @iruga7379 2 роки тому +1

    OMFG please keep your content comming...im having a blast learning from you man. Im deeply grateful for all your lessons.

  • @DanielOliveira-ru7mt
    @DanielOliveira-ru7mt Рік тому +34

    Thanks Johnny Sins

    • @lyrixvibz
      @lyrixvibz 3 місяці тому +1

      Please be polite with your words👍

    • @1blkvinci
      @1blkvinci 2 місяці тому +1

      @@lyrixvibzhe said thank you

    • @lyrixvibz
      @lyrixvibz 2 місяці тому +1

      @@1blkvincido you know Johnny sins?💀

    • @SifatUllah-12
      @SifatUllah-12 Місяць тому

      ​@@1blkvinciThat's not the right way to say thank you.

  • @olivierbegassat851
    @olivierbegassat851 Рік тому +2

    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 🙂

  • @harlockgaming1476
    @harlockgaming1476 9 місяців тому

    Love the Kramer picture in the back, my grandpa has one just like it! Thanks for the amazing videos!

  • @scottcarter4526
    @scottcarter4526 Рік тому +1

    Might also be worth mentioning that you can use == with enum's as well.

  • @WildNature170
    @WildNature170 Рік тому

    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!!!!

  • @the_Spartan_117
    @the_Spartan_117 Рік тому

    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!

  • @enfieldli9296
    @enfieldli9296 2 роки тому

    Wow, noob here, didnt know those details till you explain it, massive thanks John!

  • @eshwarnag
    @eshwarnag 10 місяців тому

    the last part was really good!

  • @jesusromero71
    @jesusromero71 2 роки тому +2

    tus videos tienen un gran valor, muchas gracias por compartir tu conocimiento

  • @brunomartel4639
    @brunomartel4639 11 місяців тому +1

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

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

  • @colonelh.s.l.3834
    @colonelh.s.l.3834 Рік тому +1

    This is awesome! Can you do a video on priority queues and comparators, and how they come together?

  • @bextrekks8354
    @bextrekks8354 2 роки тому

    lmao, that head pop up at the beginning cracks me up!

  • @cryptoInNutshellR
    @cryptoInNutshellR Рік тому

    Thanks. Useful, however you still did not cover how to compare 2 objects on the Dog example staring from 05:08

  • @Amy-zb4iq
    @Amy-zb4iq 2 роки тому +1

    What’s the codes for .equals() in class Dog?

  • @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 ==

  • @hba6018
    @hba6018 2 роки тому

    String Pool, the place where are inline strings are saved, that's why you use new String("hello")

  • @technicalboy1816
    @technicalboy1816 2 роки тому

    I wish you were my lecturer at Uni. You have talent man!

  • @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 ❤

  • @michael_scarn_
    @michael_scarn_ Рік тому

    Thanks John, your tutorials are very helpful. You are a great teacher, hats off!

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

  • @simonjunior184
    @simonjunior184 3 роки тому +7

    Amazing explanation. My Uni java lecturer even didn't taught us this important concept. Keep up the great job!

  • @Eduardado
    @Eduardado 2 роки тому +1

    Very clear. Awesome examples and also my eyes love the dark theme ^^

  • @lamaspacos
    @lamaspacos 6 місяців тому

    This channel is very very good.

  • @surkesden
    @surkesden 2 роки тому +1

    Good explanation! What about enum comparation? What should I use?

  • @amaralensheriff
    @amaralensheriff Рік тому

    Thanks John, your tutorials are awesome.

  • @InfiniteWisdom1.0
    @InfiniteWisdom1.0 9 місяців тому

    Thank you so much, your videos are pretty helpful 😊

  • @YusufDemir-gx7he
    @YusufDemir-gx7he 2 роки тому

    It seems I've found my coding channel. Thanks for the video :)

  • @علیحمیدی-س2ر
    @علیحمیدی-س2ر Рік тому

    Thx for your clear presentation Sir

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

  • @Coccoutube
    @Coccoutube Рік тому

    Thanks John!

  • @anubhavsingh2916
    @anubhavsingh2916 Рік тому

    To the point explanation

  • @wayneinteressierts9973
    @wayneinteressierts9973 Рік тому

    Great video as always. Thank you for your dedication!

  • @unknownzodiac9134
    @unknownzodiac9134 Рік тому

    Did he ever make that video on how to write a good equal method for your class?

  • @bhagyakavijan9014
    @bhagyakavijan9014 2 роки тому

    Thank you so much.. Your explanation is very clear...!!!

  • @anjelomanoranjan
    @anjelomanoranjan Рік тому

    Thanks! Your videos are great!

  • @Daryl482
    @Daryl482 Рік тому

    Hi~ What's your coding software? looks very pretty.😀

  • @mehdibash
    @mehdibash Рік тому

    == is relevant to compare enums, too

  • @adeebalaifan8684
    @adeebalaifan8684 2 роки тому

    Perfect concept

  • @Nezgul1
    @Nezgul1 2 роки тому +1

    And what with Enum ?

  • @vibhorkumar2673
    @vibhorkumar2673 2 роки тому

    How to input a single character directly? (without waiting for user to press enter key) in Java.

  • @adamlasry5225
    @adamlasry5225 2 роки тому

    Great lessons as usual. Thanks.

  • @akinyeleoluwafemi7007
    @akinyeleoluwafemi7007 2 роки тому

    It all boils down to the fact that strings are immutable right?

  • @thegloriousgoldeneagle
    @thegloriousgoldeneagle 8 місяців тому

    I love your videos, thank you

  • @vaibhavgupta973
    @vaibhavgupta973 6 місяців тому

    thanks

  • @findlestick
    @findlestick 3 роки тому

    This is a very useful video.

  • @zitronenwasser
    @zitronenwasser 3 роки тому

    So it's basically like pointers in c++? got it.

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

  • @dylangovender
    @dylangovender 2 роки тому

    Amazing tutorial!

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

  • @borisvasilev4893
    @borisvasilev4893 Рік тому

    Really Really cool!

  • @pedroaboffa
    @pedroaboffa 2 роки тому

    Thank you john!!

  • @AHMED-ry2gy
    @AHMED-ry2gy 2 роки тому

    dude, your videos are amazing

    • @pankajthorat4606
      @pankajthorat4606 2 роки тому

      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.

  • @viv7531
    @viv7531 2 роки тому

    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?

    • @matteoZattera
      @matteoZattera 2 роки тому

      It just opens the file where .equals is defined, just close this file

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

  • @radhemohannaamhai
    @radhemohannaamhai 2 роки тому +1

    Man they rejected me yesterday based on this question

  • @GayAnnabeth
    @GayAnnabeth 2 роки тому

    welllllll
    == is fine for enums

  • @GaryChike
    @GaryChike 2 роки тому

    This is a gotcha for those coming from C#. Great explanation John!

  • @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"; ??

  • @alexal8088
    @alexal8088 11 місяців тому

    is the word string pronounced SHtring in English?

  • @dhawalparmar7117
    @dhawalparmar7117 2 роки тому

    Hmm interesting video you are posting

  • @BennyAshurov
    @BennyAshurov 2 роки тому

    john are using Eclipse

    • @CodingWithJohn
      @CodingWithJohn  2 роки тому

      In this one yes, but in more recent videos I've switched to IntelliJ since I found that most viewers use that.

    • @BennyAshurov
      @BennyAshurov 2 роки тому

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

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

  • @bellum_7997
    @bellum_7997 2 роки тому

    nice one John :)

  • @xavier2586
    @xavier2586 2 роки тому

    Goldmine

  • @xirado2538
    @xirado2538 2 роки тому

    Sidenote: You can also == Enums in Java, you forgot to mention that

  • @krystianssonek
    @krystianssonek 2 роки тому

    love u

  • @vasimmalekbecomp7065
    @vasimmalekbecomp7065 2 роки тому

    Johnny Sins star of adult star is (.equals) john the star of programming world /*for me at least i guess*/.

  • @niccster1061
    @niccster1061 2 роки тому

    Why do you say "equals" instead of "gets" when assigning variables

    • @rufusneumann9703
      @rufusneumann9703 2 роки тому

      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.

    • @niccster1061
      @niccster1061 2 роки тому

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

    • @rufusneumann9703
      @rufusneumann9703 2 роки тому +2

      @@niccster1061 Interesting claim from you that his should be the CORRECT way to pronounce. Never heard it in my life.

    • @niccster1061
      @niccster1061 2 роки тому

      @@rufusneumann9703 i mean it makes alot more logical sense than saying "equals" and its also much shorter

    • @baskarnatarajan9566
      @baskarnatarajan9566 2 роки тому

      String store string pool if same value then memory location how it will show false when we compare ??????

  • @Ccck.
    @Ccck. 8 місяців тому

    bro why you look like johnny sins

  • @Daresigmally
    @Daresigmally Рік тому +24

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

  • @Visionist
    @Visionist 3 роки тому +16

    Simple and easy to understand. Thank you!

  • @magicalhats
    @magicalhats 2 роки тому +12

    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.

  • @ovey2214
    @ovey2214 2 роки тому +7

    That was incredibly well explained! Thanks a lot!

  • @brtkgromek
    @brtkgromek 2 роки тому +4

    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! :)

  • @InfoBuzz1130
    @InfoBuzz1130 Рік тому +1

    Hey pls make video on comparable comparator interface in java

  • @binilgeorge7358
    @binilgeorge7358 2 роки тому +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 🙂
      ua-cam.com/video/Bj9Mx_Lx3q4/v-deo.html

  • @GenjaOrigins
    @GenjaOrigins 2 роки тому +3

    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

  • @danielcommins1285
    @danielcommins1285 2 роки тому +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!

  • @bhukyasharath2015
    @bhukyasharath2015 Рік тому +1

    Superb sir❤

  • @MasonJF
    @MasonJF 2 роки тому +1

    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 ?

  • @HackInTheBoxx
    @HackInTheBoxx 2 роки тому +1

    Can you do a video sometime on instanceof, thank you.

  • @iyhan1987
    @iyhan1987 2 роки тому +1

    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?

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

  • @yuriytheone
    @yuriytheone Рік тому

    Strings might be equals using == operator if Java had operator's overloading like C++ has.

  • @akna1987
    @akna1987 6 місяців тому

    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

  • @matteoZattera
    @matteoZattera 2 роки тому

    Why the equals method inside Dog class take an Object type parameter instead of a Dog type parameter?

  • @syedmujtaba727
    @syedmujtaba727 2 роки тому +1

    holy shit that was an awesome explanation!!!!!!! what a goat!

  • @manishvashishth2663
    @manishvashishth2663 2 роки тому

    What about StringBuilder & StringBuffer ??

  • @wojtekzajaczkowski280
    @wojtekzajaczkowski280 Рік тому

    String word = "something";
    is primitive type
    but still can use .equal() like it was an object 😂