This is part of a brief series on Good Habits For Java Programmers.
Consider this:
if (isValid == true) {
System.out.println("The input is valid.");
}
This won't do anything differently from this variant:
if (isValid) {
System.out.println("The input is valid.");
}
Similarly,
if (isValid == true && isNew == true) {
System.out.println("The input is valid and new.");
}
won't do anything differently from
if (isValid && isNew) {
System.out.println("The input is valid and new.");
}
Use the versions that don't tack on the == true
. That's what Java programmers do, conventionally, and the shorter expressions are simpler to read. Well, they're simpler to read once you get the hang of things. Admittedly, you might find it easier to insert a secret "equals true" when reading these boolean expressions to yourself. I did when I was starting out. But, conventionally, we don't write our boolean expressions that way.
Similarly, for false
checks, we don't, conventionally, write
if (isValid == false && isNew == false) {
System.out.println("The input is not valid and not new.");
}
We write
if (!isValid && !isNew) {
System.out.println("The input is not valid and not new.");
}
Out loud, professionally, we read this as "if not isValid and not isNew then..." But if you need to mentally adjust that to "if isValid is false and isNew is false then..." that's perfectly fine. Lots of folks do. But the Java is written using the not operator, !
.
Top comments (0)