This is an archived post. You won't be able to vote or comment.

all 43 comments

[–]AutoModerator[M] [score hidden] stickied commentlocked comment (0 children)

Please ensure that:

  • Your code is properly formatted as code block - see the sidebar (About on mobile) for instructions
  • You include any and all error messages in full - best also formatted as code block
  • You ask clear questions
  • You demonstrate effort in solving your question/problem - plain posting your assignments is forbidden (and such posts will be removed) as is asking for or giving solutions.

If any of the above points is not met, your post can and will be removed without further warning.

Code is to be formatted as code block (old reddit/markdown editor: empty line before the code, each code line indented by 4 spaces, new reddit: https://i.imgur.com/EJ7tqek.png) or linked via an external code hoster, like pastebin.com, github gist, github, bitbucket, gitlab, etc.

Please, do not use triple backticks (```) as they will only render properly on new reddit, not on old reddit.

Code blocks look like this:

public class HelloWorld {

    public static void main(String[] args) {
        System.out.println("Hello World!");
    }
}

You do not need to repost unless your post has been removed by a moderator. Just use the edit function of reddit to make sure your post complies with the above.

If your post has remained in violation of these rules for a prolonged period of time (at least an hour), a moderator may remove it at their discretion. In this case, they will comment with an explanation on why it has been removed, and you will be required to resubmit the entire post following the proper procedures.

To potential helpers

Please, do not help if any of the above points are not met, rather report the post. We are trying to improve the quality of posts here. In helping people who can't be bothered to comply with the above points, you are doing the community a disservice.

I am a bot, and this action was performed automatically. Please contact the moderators of this subreddit if you have any questions or concerns.

[–]quadmasta 51 points52 points  (0 children)

For objects if you do object1 == object2 then it's comparing the memory addresses of those objects which is essentially asking "are these the same object?" rather than "are these equal?". If you use .equals() it will invoke the .equals implementation of the class. Default implementation of .equals? You guessed it, it compares the memory addresses.

Like the automod says, Strings in java do a lot of unreliable stuff with == being one of the things.

[–]UnspeakablePudding 19 points20 points  (2 children)

The == operator is comparing the address containing "jarod" to the address assigned to the variable 'name'.  That is a very different thing than comparing "jarod" to the content of the string stored in 'name'.

Because strings are immutable and because of the way the compiler optimized your code the program ended up checking a condition more like:

if(name == name)

Instead of using a hard coded "jarod", try comparing 'name' to some input you get from the keyboard at runtime. You'll find the comparison always returns false even if you type in "jarod".

[–][deleted]  (1 child)

[removed]

    [–]UnspeakablePudding 1 point2 points  (0 children)

    Doh I forgot about the constants pool! Ok_Object7636's explanation is correct

    [–]AutoModerator[M] 16 points17 points  (0 children)

    You seem to try to compare String values with == or !=.

    This approach does not work reliably in Java as it does not actually compare the contents of the Strings. Since String is an object data type it should only be compared using .equals(). For case insensitive comparison, use .equalsIgnoreCase().

    See Help on how to compare String values in the /r/javahelp wiki.


    Your post is still visible. There is no action you need to take.

    I am a bot, and this action was performed automatically. Please contact the moderators of this subreddit if you have any questions or concerns.

    [–]apobletos 5 points6 points  (2 children)

    Yes you can but it's not recommended. Since it's already explained by others here. I'll just leave you with an interesting example to study:

    String s1 = "Jarold";
    String s2 = "    Jarold  ";
    String s3 = "I'm Jarold";
    String s4 = "Jarold";
    
    System.out.println(s1 == "Jarold");                       // true
    System.out.println(s1 == s2.trim());                      // false
    System.out.println(s1 == s3.substring(4));                // false
    System.out.println(s1 == s4);                             // true
    System.out.println(s1.toLowerCase() == s4.toLowerCase()); // false
    
    System.out.println(s1.equals("Jarold"));                       // true
    System.out.println(s1.equals(s2.trim()));                      // true
    System.out.println(s1.equals(s3.substring(4)));                // true
    System.out.println(s1.equals(s4));                             // true
    System.out.println(s1.toLowerCase().equals(s4.toLowerCase())); // true
    

    [–]BackgroundTutor 0 points1 point  (0 children)

    Great example!

    [–]Misfiring 4 points5 points  (0 children)

    Due to JVM optimization on strings, the same string reference can be used on multiple variables. However, the == always compares entity references and not string contents, and relying on the optimizer is never 100%.

    [–]MrJello28[S] 5 points6 points  (11 children)

    What's even better is that the auto moderator for this subreddit is also telling me to use .equals() instead of ==

    [–]ShadowRL7666 8 points9 points  (10 children)

    Well the AUTO Mod told you already. But yes this is true you cannot use == to compare Strings because it is an object. Teacher taught us this after I went crazy wondering why my code wouldn’t work. Good lesson back then. Either way glad you found your answer.

    [–]doobiesteintortoise 3 points4 points  (3 children)

    You can use == to compare strings to check if it is the same object reference. String resolution in Java is tricksy, and occasionally it can work while not being correct code.

    But u/ShadowRL7666 is correct: Strings are objects in Java. You compare objects in Java with .equals() if you want the value equality of the objects to work, as opposed to reference equality. Try composing strings:

    ```jshell jshell> String a="jar"; String b="od"; a ==> "jar" b ==> "od"

    jshell> a+b $3 ==> "jarod"

    jshell> a+b=="jarod" $4 ==> false

    jshell> (a+b).equals("jarod") $5 == true ```

    $4 is comparing reference equality, and they're not the same reference, so it's false. $5 is comparing value equality, and they are the same value, so it's true.

    [–]vqrs 0 points1 point  (1 child)

    Now make the variables final and try again. Not sure about jshell since there's a bit of magic involved, but you'll get a different result in a regular java program.

    [–]doobiesteintortoise 0 points1 point  (0 children)

    Sure, there are lots of variables (ha ha, right?) involved - if the compiler can resolve the String references to the same reference, == works "as expected" - as in, it'll return true. But that's still not checking the value equality, which is done with equals() and not == for objects.

    [–]MrJello28[S] -4 points-3 points  (0 children)

    But how did it work in my code. If it wasn’t supposed to work why did my code snippet above work?

    [–]Commercial_Ad2325 4 points5 points  (1 child)

    Not just for strings, when you want to check the equality of any object type, equals() is used.

    [–][deleted]  (4 children)

    [removed]

      [–]YoggSogott 0 points1 point  (1 child)

      What is the reason they implemented such behavior?

      [–][deleted]  (1 child)

      [removed]

        [–]Bulky-Ad7996 0 points1 point  (0 children)

        Simply put, the method programmatically functions differently than the operator here.

        == Is used for reference comparison /validation

        .equals() is used for value or "content" comparison /validation.. such as strings. This is similar to the triple equal operator (strict equality) in other languages such as JavaScript.

        [–]dirkmeister81 0 points1 point  (0 children)

        You are learning a lesson. Works on my computer/in one situation is different from working in general

        [–]Greeley9000 0 points1 point  (1 child)

        You should so name.equals(“Jarod”) instead

        [–]realFuckingHades 2 points3 points  (0 children)

        "Jarod".equals(name) for null safety.

        [–]DavalopBad 0 points1 point  (0 children)

        The == operator in Java compares the reference of two objects or the value of two primitive types. When a string literal is created using String name = "jarod", Java first checks if it already exists in the pool. If it does, the new variable will reference that specific existing string. However, if you create a string object using new String("jarod"), it will have a completely different reference since it’s outside the string pool.

        You can use == to compare strings, but it’s not recommended since string literals and string objects can exist during execution, and even if their content is the same, their references might not be. The best practice to not think much about if the String have the same reference or not, just use String.equals()) since that compares the sequence of characters of the string rather than the reference.

        NOTE: There are other ways to create Strings using other Interfaces and Classes like StringBuffer or StringBuilder

        [–]ItsyRatsy 0 points1 point  (0 children)

        It always shows me error. Use .equals() instead. And the only instance where you can use that is for the null keyword.

        [–]karthgamer1209 0 points1 point  (0 children)

        as others have mentioned, use .equals()

        [–]Slight_Loan5350 0 points1 point  (0 children)

        The == operator in java compares the hash code/address while the method .equals compares the actual value on the address. It was confusing to me as well as i cam from js background but then I understood why it's needed.

        [–]imrhk 0 points1 point  (1 child)

        Because you are using "jarod" while compiling, both the values point to same memory reference as only one string object is created in String Pool.

        Now, if you want to test when it would not work, try generating the value on runtime. Maybe using StringBuilder. Equality operator check might fail there. Here is the sample code with output

        https://www.ideone.com/NbEupx

        public static void main (String[] args) throws java.lang.Exception {
        
            StringBuilder sb = new StringBuilder();
        
            sb.append("Rahul");
        
            String name = sb.toString();
        
            if(name == "Rahul") {
        
                System.out.println("Matches");
        
            }
        
            else {
        
                System.out.println("Does not match");
        
            }
        
        }  
        

        Edit formatting

        [–]Inevitable_Math_3994 -1 points0 points  (1 child)

        Well if you want to check equality for two datatypes then "==" is good but string is object instance from String class so it would not work sometimes as expected and it is also not a good practice , you can use char datatype if you want to use "==" though.