• Post Reply Bookmark Topic Watch Topic
  • New Topic

Confused over '==' and '.equals'

 
Fergus Flanagan
Ranch Hand
Posts: 41
1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
This code extract works fine...




and yet in the extract below it fails to find a match when there was one, it will work if I use .equals instead of '=='...
'contArrayL' is an arraylist of 'Contacts' objects
'c' is an object of type 'Contacts' that I'm searching for





I was told by my tutor ....
You don't use == on objects, full stop.  Unless you want to be checking if the memory locations are the same.
.equals is what you use for objects.
As a general rule think...
== for primitive types
.equals for objects.


When I asked why he mentioned something about literal strings being interned in Java which tbh went over my head.


So why does '==' work in the first bit of code above ::
 
Tim Cooke
Sheriff
Posts: 3457
163
Clojure IntelliJ IDE Java
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
We have a Wiki page all about that: Avoid The Equality Operator
 
Campbell Ritchie
Marshal
Posts: 53140
124
  • Likes 3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Start by reading our FAQ about == and the old JavaRanch Journal article by Corey McGlone called Strings, literally. I hope that will explain what interned Strings means. If not, ask again. Beware of subclasses of the Number class because some of their instances are interned automatically, and some are not interned. Even from the same class, e.g. Integer.

Simply, if you write "string", then all Strings derived from that will be the same object. If you write "string" elsewhere, and the JVM recognises it as the content as before, it will reuse the previous String object. If, however, you enter text from the keyboard or read it from a file, the JVM cannot predict that it will be the same content, so it uses a different instance, unless you use the intern() method on all Strings.

Simply, there are five situations when you sh‍ould use ==
  • 1: On primitives. You cannot use equals() on primitives because they don't have methods.
  • 2: When you need to see whether you have two references to the same object, and the only place you really need to do that is when writing an equals() method.
  • 3: When either of the operands is the reserved word null, == null or != null
  • 4: When either operand is a constant in an enum. Read the Java® Language Specification (=JLS). That is one of the few parts of the JLS really useful for beginners.
  • 5: “I just wanted to see what happens if I did ...” That justifies trying just about anything short of deleting every file on your hard drive
  • Never use == on the boolean literals true and false. Never
    if (b == true) ...
    but
    if (b) ...
    Neven
    if (b == false) ...
    but
    if (!b) ...
     
    Ganish Patil
    Ranch Hand
    Posts: 529
    19
    Chrome Eclipse IDE Hibernate Java jQuery MySQL Database Netbeans IDE Spring Tomcat Server
    • Likes 2
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    When I asked why he mentioned something about literal strings being interned in Java which tbh went over my head.
    Just go through this diagram I created to understand String pool concept.
    Only you have to keep in mind, when at step 4(To see step numbers, look at digits in red circle at left side) strThree.intern() If "Java" literal's reference wasn't in pool then same object i.e. having reference location 2007 would have returned.
    StringPoolInternProcess.png
    [Thumbnail for StringPoolInternProcess.png]
     
    Fergus Flanagan
    Ranch Hand
    Posts: 41
    1
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    Never use == on the boolean literals true and false. Never
    if (b == true) ...
    but
    if (b) ...
    Neven
    if (b == false) ...
    but
    if (!b) ...


    As a newbie to Java I've used '==' on booleans and it's worked fine so far




    2: When you need to see whether you have two references to the same object, and the only place you really need to do that is when writing an equals() method.
    Huh?

    Do you mean?
    When you need to see whether you have two references to the same object use '=='
    And for an objects component use .equals
     
    Fergus Flanagan
    Ranch Hand
    Posts: 41
    1
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    Tim Cooke wrote:We have a Wiki page all about that: Avoid The Equality Operator


    Wow brilliant resource
     
    Fergus Flanagan
    Ranch Hand
    Posts: 41
    1
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    Ganish Patil wrote:
    When I asked why he mentioned something about literal strings being interned in Java which tbh went over my head.
    Just go through this diagram I created to understand String pool concept.
    Only you have to keep in mind, when at step 4(To see step numbers, look at digits in red circle at left side) strThree.intern() If "Java" literal's reference wasn't in pool then same object i.e. having reference location 2007 would have returned.


    Will have to go through this later, but thank you for your help
     
    Campbell Ritchie
    Marshal
    Posts: 53140
    124
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    Fergus Flanagan wrote:. . .  I've used '==' on booleans and it's worked fine so far

    You have been lucky. If is only a matter of time before you write = and get two errors for the price of one. == true and == false are also poor style.
    . . . When you need to see whether you have two references to the same object use '=='
    And for an objects component use .equals
    Yes. The only place you really need to know whether you have the same object twice is probably the equals() method. The equals() method is not really a beginner's topic because of its difficulty.
     
    Winston Gutkowski
    Bartender
    Posts: 10573
    65
    Eclipse IDE Hibernate Ubuntu
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    Campbell Ritchie wrote:It is only a matter of time before you write = and get two errors for the price of one.

    Or, even worse, DON'T get an error, but create an unintended bug.

    Winston
     
    Mike London
    Ranch Hand
    Posts: 1290
    6
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    Winston Gutkowski wrote:
    Campbell Ritchie wrote:It is only a matter of time before you write = and get two errors for the price of one.

    Or, even worse, DON'T get an error, but create an unintended bug.

    Winston


    I see what you mean about potentially using "=" instead of "==" by mistake, but on the other hand, if (b==true) is more self-documenting code than if (b).

    Other than the potential mistake of "=" instead of "==", I tend to like the if (b == true) since it's clear what's going on in the code.

    Can you list another reason to use the more terse if (b)?

    - m

     
    Knute Snortum
    Sheriff
    Posts: 3326
    84
    Chrome Eclipse IDE Java Postgres Database VI Editor
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    if (b==true) is more self-documenting code than if (b).

    I don't think so:
     
    Campbell Ritchie
    Marshal
    Posts: 53140
    124
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    Mike London wrote:. . . if (b==true) is more self-documenting code than if (b). . . .
    Disagree. Once one has understood the concept of a predicate, the == true becomes obviously redundant.

    Knute obviously thinks so, too.
     
    Campbell Ritchie
    Marshal
    Posts: 53140
    124
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    Winston Gutkowski wrote:. . . Or, even worse, DON'T get an error, but create an unintended bug. . . .
    I obviously wasn't clear; I meant a logic error causing incorrect results, which does not so much translate to a bug, but two bugs for the price of one.
     
    Mike London
    Ranch Hand
    Posts: 1290
    6
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    Campbell Ritchie wrote:
    Winston Gutkowski wrote:. . . Or, even worse, DON'T get an error, but create an unintended bug. . . .
    I obviously wasn't clear; I meant a logic error causing incorrect results, which does not so much translate to a bug, but two bugs for the price of one.


    Of course, code like this makes me rethink my position:



    // Prints "True", of course.

    -------

    I'm going to rethink my position on the "==" for comparing Booleans and agree with you.

    Nice little tip here.

    - mike
     
    Tim Cooke
    Sheriff
    Posts: 3457
    163
    Clojure IntelliJ IDE Java
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    Mike London wrote:but on the other hand, if (b==true) is more self-documenting code than if (b).

    In my opinion you're trying to fix the wrong problem here. If you're considering qualifying the state of a boolean expression with (b == true) then that points to another problem, which is that the boolean variable is poorly named. As you go on to demonstrate in your more recent post, a boolean variable name such as found or isFound is more expressive in itself and as such often does not need the (isFound == true) qualifier.
     
    Campbell Ritchie
    Marshal
    Posts: 53140
    124
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    Tim Cooke wrote:. . . the boolean variable is poorly named. . . .
    I usually simply write b as a generic name for any boolean. Knuet's example with a good variable name makes that point clear.
     
    Campbell Ritchie
    Marshal
    Posts: 53140
    124
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    I have enhanced your code to show that you can get any number of logic errors following that mistaken assignment.
    Mike London wrote:. . . "==" for comparing Booleans and agree with you. . . .
    Careful about spellings; you probably mean booleans not Boolean.
     
    Mike London
    Ranch Hand
    Posts: 1290
    6
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    Campbell Ritchie wrote:I have enhanced your code to show that you can get any number of logic errors following that mistaken assignment.
    Mike London wrote:. . . "==" for comparing Booleans and agree with you. . . .
    Careful about spellings; you probably mean booleans not Boolean.


    I wasn't trying to write elegant code; rather, just demonstrate the single issue described.

     
    Mike London
    Ranch Hand
    Posts: 1290
    6
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    I wanted to also add for the "OP" that if you use an IDE plug-in to check over your source code, like PMD, you would get a code warning about doing assignments in if statements with booleans using my simple code above.

    -mike
    PMD-Warning.png
    [Thumbnail for PMD-Warning.png]
     
    Knute Snortum
    Sheriff
    Posts: 3326
    84
    Chrome Eclipse IDE Java Postgres Database VI Editor
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    And if you happen to be using Eclipse, you can do this without a plugin:

    Windows > Preferences > Java > Compiler > Errors/Warnings.  Look under Potential programming problems.
     
    Mike London
    Ranch Hand
    Posts: 1290
    6
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    Knute Snortum wrote:And if you happen to be using Eclipse, you can do this without a plugin:

    Windows > Preferences > Java > Compiler > Errors/Warnings.  Look under Potential programming problems.


    Interesting.

    I thought Intellij's code highlighting might have that too, but I didn't find it.

    PMD rocks so I would prefer it as part of the code review process anyway.

     
    Campbell Ritchie
    Marshal
    Posts: 53140
    124
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    Mike London wrote:. . . Of course, code like this makes me rethink my position: . . .
    I have linked to that post elsewhere so for that post.
     
    What are you doing? You are supposed to be reading this tiny ad!
    the new thread boost feature brings a LOT of attention to your favorite threads
    https://coderanch.com/t/674455/Thread-Boost-feature
    • Post Reply Bookmark Topic Watch Topic
    • New Topic
    Boost this thread!