23

Been programming Java for a few weeks now, and WTF is this, Java?!
"Example".equals("Example")

What is wrong with the form that a dozen of other languages use?
"Example" == "Example"

P. S. If you don't know Java, the latter one compares for the type of objects and always returns true in this case.

Comments
  • 4
    @Kushtrim Yeap, the problem is that it will ALWAYS return true. Even this in Java is true:
    "Trump" == "Hillary"
  • 4
    == compares object to object so its only true if the two are the same object.
    Because string literals usually cached, they appears to be the same object. Hence 'a' == 'a' is true but 'a' == 'b' is false.
    .equals on the other hand compares object by value.
    And for 'Why not use == instead of .equals and === for object comparsion?'
    Because you might want to override equality but Java dont have operator overloading, so .equals was the solution.
  • 2
    As for why Java don't have operator overloading, I dont know.
  • 0
    As far as I know thats only for strings and only because + compiles to StringBuilder. But you cant define custom overloads
  • 0
    Java doesn't have === because it doesn't need to. == compares type as well. 1 =='1' is false.
  • 0
    @jirehstudios the point is depending on how it is built

    When using == in java Two different string objects whose values are the same, would return false.
  • 0
    @brettmoan would you ever have two different string literal with the same value? I thought all references to strings with the same value would be pointing to the same strings?
  • 0
    == compares type in most languages, and === compares type and identity in most languages.
  • 0
    @MindfulMinun just to be clear, it does compare value as well right? I mean in general "foo" == "bar" would not be true just because they share the same type, right?
  • 2
    @siljamicke == only compares the reference of an object. It completely ignores the value and returns true if both sides refer to the same object.

    It does compare values if you use primitives though.
  • 0
    @java9 i was speaking in general terms. I guess what you're saying is correct in Java. But how on earth would "foo" == "bar" ever evaluate to true in any language?
  • 1
    @siljamicke sorry, you are right about that of course! I for sure wouldn't understand why.
  • 2
    @java9 read the above with respect to what was said further above, that the == operator compares type. If that would be the case anystring == anyotherstring should evaluate to true. I find that hard to believe...
  • 1
    @siljamicke Yes I think type isn't quite the right word to use there. I assume the intended meaning was value.
  • 3
    I'd love to know where the idea of '== compares types' came from. It's not even close! For anyone who wants to know the truth - http://stackoverflow.com/questions/...
Add Comment