Java Reference
In-Depth Information
} else if (x == 4) {
return 4;
} else if (x == 5) {
return 5;
}
If you always want to return the value of x , you should just say:
return x;
A similar confusion can occur when students use boolean variables. In the last
section we looked at a variation of the cumulative sum algorithm that used a
boolean variable called negative to keep track of whether or not the sum ever goes
negative. We then used an if/else statement to print a message reporting the result:
if (negative) {
System.out.println("Sum went negative");
} else {
System.out.println("Sum never went negative");
}
Some novices would write this code as follows:
if (negative == true) {
System.out.println("Sum went negative");
} else {
System.out.println("Sum never went negative");
}
The comparison is unnecessary because the if/else statement expects an expres-
sion of type boolean to appear inside the parentheses. A boolean variable is already
of the appropriate type, so we don't need to test whether it equals true ; it either is
true or it isn't (in which case it is false ). To someone who understands Boolean
Zen, the preceding test seems as redundant as saying:
if ((negative == true) == true) {
...
}
Novices also often write tests like the following:
if (negative == false) {
...
}
Search WWH ::




Custom Search