8

I spent 20 minutes looking at my Java if statement wondering why it's not working as intended:
if (word == "ABC")
I need some sleep/more coffee 🙃

Comments
  • 0
    If you are using IntelliJ then install SonarLint plugin. It will save you some hours of sleep now and then. I only have good things to say about that plugin
  • 0
    “ABC” is a literal, probably initialized in the stack (Java has a funky way of storing objects that aren’t instantiated).

    word, I’m guessing is an object. Their address will definitely not be the same. Their value might.

    .equals() FTW

    hehe.
  • 0
    I was partially wrong. Because “abc” is in fact a literal/constant in this case, it is interned. So another string literal can be compared using ==, but a string object can’t (you have to use .equals())

    String aWord = “abc”;
    String bWord = new String(“abc”);

    aWord == “abc”; //true aWord == bWord; //false
    bWord == “abc”; //false
    bWord.equals(“abc”); //true
Add Comment