Booleans and returns - java

public boolean percentDepreciatedOutOfRange() {
if (percentDepreciated < DEPRECIATION_MIN || percentDepreciated > DEPRECIATION_MAX) {
return true;
}
else {
return false;
}
}
Can the code above be written without the else statement and just have return false; after the if statement and still have the same result? If so, why? This is what I mean
public boolean percentDepreciatedOutOfRange() {
if (percentDepreciated < DEPRECIATION_MIN || percentDepreciated > DEPRECIATION_MAX) {
return true;
}
return false;
}

You should just write
public boolean percentDepreciatedOutOfRange() {
return percentDepreciated < DEPRECIATION_MIN || percentDepreciated > DEPRECIATION_MAX);
}
which is more readable. Avoid statements like
If (xxx) { return true; }
else { return false; }
because the if just adds noise around the expression.
The reason why this is legal is that the boolean type is the same in evaluating the if expression and in the return type of the method.

Because return actually exits the function (method).
In the case the if is not entered the rest of the code will execute normally.
Since you have boolean returns, having return false at the end of the function, means everything up to the end failed.
You could even rewrite it to:
public boolean percentDepreciatedOutOfRange() {
if (percentDepreciated < DEPRECIATION_MIN) {
return true;
}
if (percentDepreciated > DEPRECIATION_MAX) {
return true;
}
return false;
}
To clearly state the tests in the method.

Another way I like:
Defining return variable as 1st statement with default value.
Change the variable in method in various biz logic
Return the variable value (Single return statement)
public boolean percentDepreciatedOutOfRange() {
boolean status = false;
status = percentDepreciated < DEPRECIATION_MIN || percentDepreciated > DEPRECIATION_MAX;
return status;
}

Related

Why do I get a missing return statement error although there is a return statement in each of my if and if else blocks?

What I am trying to do here out of flower1 and flower2, one is even and one is odd then return true.
If both are even, return false.
If both are odd, return false.
When my code is:
public class OppositesAttract {
public static boolean isLove(final int flower1, final int flower2) {
if(flower1%2==0 && flower2%2==0){
return false;
}else
if(flower1%2!=0 && flower2%2!=0){
return false;
} else
if(flower1%2==0 || flower2%2==0){
return true;
}
}
}
I get a "missing return statement" error.
So I added:
public class OppositesAttract {
public static boolean isLove(final int flower1, final int flower2) {
if(flower1%2==0 && flower2%2==0){
return false;
}else
if(flower1%2!=0 && flower2%2!=0){
return false;
} else
if(flower1%2==0 || flower2%2==0){
return true;
}else{
return true;
}
}
}
Now, the code works but I do not understand why I have to add the additional return statement.
The compiler doesn't know the first 3 terms cover all situations.
if(flower1%2==0 && flower2%2==0){
return false;
} else if(flower1%2!=0 && flower2%2!=0){
return false;
} else if(flower1%2==0 || flower2%2==0){
return true;
}
to you this reads as: all options are covered. but the compiler just sees:
if (somethingThatMayBeTrue) {
} else if (somethingElseThatMayBeTrue) {
} else if (aThirdThingThatMayBeTrue) {
} .... and what if none of them are?
You may know that the last else if should always be true (since you know they are not both uneven) but the compiler doesn't generally try to understand your code.
in your case, the last clause (aThirdThingThatMayBeTrue, flower1%2==0 || flower2%2==0) is actually (somethingThatIsAlwaysTrueIfPreviousTermsAreFalse).
so you can treat it as such:
if(flower1%2==0 && flower2%2==0){
return false;
} else if(flower1%2!=0 && flower2%2!=0){
return false;
} else {
return true;
}

Loop: This method must return a result of type boolean

This is the error I get:
This method must return a result of type boolean
And this is the code:
public boolean seleccionar(Aeronave otra) {
for (int i = 0; i < this.as.length; i++) {
if (otra != null && !otra.equals(this.as[i]) && otra.amenazadaPor(this.as[i])) {
return true;
} else {
return false;
}
}
}
Add a return false before the last brace. Your function doesn't return anything if this.as.length == 0, and Java is giving a compile error because of that.
The issue is that it is possible that the for-loop will loop through all elements and eventually reach the end and no result is returned. In this case we return false to ensure this.
public boolean seleccionar (Aeronave otra) {
for (int i=0; i < this.as.length; i++) {
if (otra !=null && !otra.equals(this.as[i]) && otra.amenazadaPor(this.as[i])) {
return true;
}
}
return false;
}
Your code will exit on first loop element. But when array this.as is empty, so loop will not execute, then your function is missing a return value -therefore compiler does not allow this.
To solve this issue, simply move return false after the loop ends.
public boolean seleccionar (Aeronave otra) {
for (int i=0; i < this.as.length; i++) {
if (otra !=null && !otra.equals(this.as[i]) && otra.amenazadaPor(this.as[i])) {
return true;
}
}
return false; // if no elements are matching loop condition, return false
}}

writing a java method that returns a boolean from a search

I have written a method that searches a tree to test if any integers are negative.
But I am struggling to get the right Boolean value returned. Any pointers as to where I am going wrong?
What I want to achieve is that as soon as the condition statement is met a false is returned but unfortunately my code is always returning a true
static boolean allE(Tree<Integer> x) {
if (x.isEmpty()) return true;
else {
if (x.getValue()%2 != 0) return false;
}
allE(x.getLeft());
allE(x.getRight());
return true;
}
When you recurse on allE you need to consider the result of that recursion. Easiest fix I see, change
allE(x.getLeft());
allE(x.getRight());
return true;
to
return allE(x.getLeft()) && allE(x.getRight());
Although, I think it makes more sense to write the algorithm such that you recurse on even explicitly. And allE saves three letters compared to allEven (please use meaningful names for methods and variables). Something like,
static boolean allEven(Tree<Integer> node) {
if (node.isEmpty()) {
return true;
} else if (node.getValue() % 2 == 0) {
return allEven(node.getLeft()) && allEven(node.getRight());
}
return false;
}
You're not using the results of your recursive tests properly.
It should be:
if (x.isEmpty()) {
return true;
}
boolean thisNodeEven = x.getValue() % 2 == 0;
return thisNodeEven && allE(x.getLeft()) && allE(x.getRight());
I suppose you need to evaluate the return-value of the recursive calls:
static boolean allE(Tree<Integer> x)
{
if (x.isEmpty())
return true;
else {
if (x.getValue()%2 != 0) return false;
}
if(!allE(x.getLeft()) || !allE(x.getRight()))
return false;
return true;
}

function requiring more than one return statements

I am posting here two functions. In the findPrime(int m, int i, int n) I have one outer if and outer else block from both the block I am getting return so it can be considered that the function is returning something I put same structure in endOther(String a, String b) i.e.
there are two main if-else blocks both are returning value as per function's return type so we can say that function is returning something but the endOther(String a, String b)
function is throwing compile time error saying that put return statement while first function is not throwing such error. I am not understanding this issue please help me. Type both the functions in eclipse and check
1.
static boolean findPrime(int m, int i, int n){
if(n == 0 || n == 1)
return false;
else {
if(i <= m) {
if(n%i == 0)
//if(m%i == 0)
return false;
else {
i++;
//return findPrime(m,i);
return findPrime(m,i,n);
}
}
else {
return true;
}
}
}
2.
public boolean endOther(String a, String b) {
if(a.length()==b.length()) {
if(a.equals(b))
return true;
else
return false;
}
else {
if(a.length()>b.length()) {
if(a.substring(a.length()-b.length(),b.length()).equals(b))
return true;
}
else {
if(b.substring(b.length()-a.length(),a.length()).equals(a))
return true;
else
return false;
}
}
}
Your endOther function must return a value on all possible execution paths. In case a.length() > b.length() the return may not be executed based on the condition of the inner if.
public boolean endOther(String a, String b) {
if(a.length()==b.length()) {
if(a.equals(b))
return true;
else
return false;
}
else {
if(a.length()>b.length()) {
// IF THIS FAILS THERE IS NO RETURN!
if(a.substring(a.length()-b.length(),b.length()).equals(b))
return true;
}
else {
if(b.substring(b.length()-a.length(),a.length()).equals(a))
return true;
else
return false;
}
}
}
As a general note, you could use some of the methods in String to improve your code, e.g. String.endsWith instead of the substring operation. This would be more readable. a and b being identical is a special case of String.endsWith, so the following should be equivalent:
public boolean endOther(String a, String b) {
return a.endsWith(b) || b.endsWith(a);
}

Boolean multireturn refactoring

What do you think will be the best way to refactor this kind of boolean method?
if (someService.isTrue(importantArg)) {
return true;
} else if (someService.isSomeTrue(anotherArg)) {
return isAnotherCondition(entry);
} else {
return super.thisMethod();
}
This is a minor refactoring, but you can remove the elses as you can't reach that code if the previous condition was true (if it was true, it would have returned a value and exited the method)
if (someService.isTrue(importantArg)) {
return true;
}
if (someService.isSomeTrue(anotherArg)) {
return isAnotherCondition(entry);
}
return super.thisMethod();
return someService.isTrue(importantArg) || (someService.isSomeTrue(anotherArg)
&& isAnotherCondition(entry)) || super.thisMethod();

Categories