Actually Netbeans was as smart as it could be. It should be like this:
return num >= 0;
Now, what is the result of the expression num >= 0
? It is a boolean, right? That is, the result of this "account" will be or false
, or will be true
. Either it is "greater than or equal to zero", or it is not, only this can occur.
So why not use this direct result? If what you need is to define a true
when this expression results in true
and you need to false
when the expression results in false
, then use the result of the expression and simplify the logic.
I understand that a lot of programmers think that the if
is a magical thing, and that you have a condition inside. In fact the if
expects a boolean expression, a conditional expression. It can be a literal, one variable simple (with boolean type value), or a complex expression whose outworking be a boolean.
All this is valid (even if the former makes no sense except for testing):
//literal
if (true)
//variável
variavel = outraVariavel > 0 && maisUmaVariavel.equals("teste");
if (variavel)
//expressão
if (outraVariavel > 0 && maisUmaVariavel.equals("teste"))
The if
serves for flow control, it decides only whether it should run a block or another, if available. The decision is made by any boolean value, where it comes from, it doesn’t matter. The code of this method does not need a flow control, it just needs a boolean result.
The same goes for the while
and for
, are only flow controls whose decision will deviate to another line or continue in the following is determined by a boolean value that can be obtained by one of the three forms cited above.
Do so by simplifying the code and getting the same result:
public boolean isPositive(float num) {
return num >= 0;
}
I put in the Github for future reference.
Further reading.