Hey everyone! Can someone help me understand the below code?
are all variables I declared earlier
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?
Shameless self-promotion: here is a guide on
boolean values, operators, and
if statements that explains what’s going on:
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.)
Here a small demo:
String a = "cat";
String b = "c";
b += "at";
println("a =", a);
println("b =", b);
println("a == b ?");
println(a == b);
prints the following:
a = cat
b = cat
a == b ?
The demo at the String documentation page no longer works as expected because of Java String interning.