#equals()

1 messages · Page 1 of 1 (latest)

tranquil vector
#

I need to compare both first and second strings. If they're == then it should be true, if not false. if both null then true. For some reason the code doesnt work

restive spearBOT
#

<@&987246399047479336> please have a look, thanks.

#

You can use </chatgpt:1108714622413963314> to ask ChatGPT about your question while you wait for a human to respond.

balmy drift
#

That will lead to a nullpointerexception.

#

You're asking something that's potentially null: am I null?

#

You can also just use Objects.equals()

tranquil vector
coarse cloak
#

FYI

if (a.equals(null) && b.equals(null)) { // NullPointerException if a or b are null
   return true; // this is never executed becuse anything.equals(null) is false.
}

if (a.equals(null) || b.equals(null)) { // NullPointerException if a or b are null
   return false; // this is never executed becuse anything.equals(null) is false.
}

And Simon_Verhoeven says, use Objects.equals(a, b) instead.

https://docs.oracle.com/en/java/javase/21/docs/api/java.base/java/util/Objects.html#equals(java.lang.Object,java.lang.Object)

plain citrus
#

what happens if you just return firstString.equals(SecondString); ???

balmy drift
#

It would also throw a NPE if firstString was null.

frigid sail
#

All that code you wrote is like Simon said, just Objects.equals(firstString, secondString)