Returning a Java Boolean Method
I have a boolean method in my Java program and am wondering why NetBeans recommends making this change to my code:
return isPrime != 0;
I wrote:
if (isPrime == 0) {
return false;
}
else{
return true;
}
Both work correctly, but I cannot understand the logic behind the changes that NetBeans offers. Neither true nor false is returned. Can anyone explain to me the logic behind this? Thanks to
source to share
Instead
if (isPrime == 0) {
return false;
} else {
return true;
}
try
return (isPrime != 0);
It's the same, I'll show you the refactoring path. Beginning with
if (isPrime == 0) {
return false;
} else {
return true;
}
coincides with
if (isPrime != 0) {
return true;
} else {
return false;
}
which can be reduced by substitution, substituting 'isPrime! = 0' with the function 'doIsPrime ()'
private boolean doIsPrime() {
return isPrime != 0;
}
substituting in
if (doIsPrime()) {
// guaranteed to be the same as above!
return doIsPrime();
} else {
return doIsPrime();
}
which can have both minified blocks (like duplicate code)
if (doIsPrime()) {
}
return doIsPrime();
And reduced further by removing the if statement around the empty block
return doIsPrime();
Now undo replacing 'doIsPrime ()' back with 'isPrime! = 0'
return isPrime != 0;
There was no need to make a replacement; but, I find it better shows that the if argument is redundant.
source to share
Doesn't return true or false.
False. Comparison result isPrime != 0
, a is boolean
returned, either true
or false
.
Can anyone explain to me the logic behind this?
The first code is equivalent to the second code. If isPrime
- 0
, return false
, else return true
. The operator !=
will give false
if isPrime
- 0
and true
if not 0
.
source to share
Just to add to that said:
While your solution and the NetBeans recommended approach are accurate, another approach would also be:
if (isPrime == 0) {
return false;
}
return true;
I don't know what NetBeans will suggest with this approach, but I guess it will offer the same recommendation as above.
source to share