What does if(!VARIABLE.equalsVARIABLE) mean?

Hey everyone! Can someone help me understand the below code?

buttonOneText
buttonTwoText
levelNumber

are all variables I declared earlier

if (!buttonTwoText[levelNumber].equals(buttonOneText[levelNumber]))

In short, when there is a ‘!’ inside the ‘if’ clause and there is also an ‘.equals’ inside the same clause. What are these doing to the ‘if’ clause exactly?

Processing.org/reference/logicalNOT.html

Shameless self-promotion: here is a guide on boolean values, operators, and if statements that explains what’s going on:

About .equals():

To compare the contents of two Strings, use the equals() method, as in if (a.equals(b)), instead of if (a == b). A String is an Object, so comparing them with the == operator only compares whether both Strings are stored in the same memory location. Using the equals() method will ensure that the actual contents are compared. (The troubleshooting reference has a longer explanation.)

(from String / Reference / Processing.org)

Here a small demo:

String a = "cat";
String b = "c";
b += "at";

println("a =", a);
println("b =", b);
println();

println("a == b ?");
println(a == b);
println();

println("a.equals(b) ?");
println(a.equals(b));

prints the following:

a = cat
b = cat

a == b ?
false

a.equals(b) ?
true

The demo at the String documentation page no longer works as expected because of Java String interning.

1 Like