Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Skip if conditions when a flag is false

Tags:

java

I have several independent if conditions and in each condition i will evaluate a boolean variable value either true or false.

if the boolean variable value gets false in the first if condition then how can i skip the rest of all conditions.

private static boolean isRecommended(Fruit fruit) {
    boolean isRecommended = true;

    if(fruit.weight > 2){
        isRecommended = false;
    }
    if(!"red".equals(fruit.color)){
        isRecommended = false;
    }
    if(!"sweet".equals(fruit.taste)){
        isRecommended = false;
    }
    if(!fruit.isPerishable){
        isRecommended = false;
    }

    return isRecommended;
}

if the first if() condition is executed then is it possible to return the value. I know in the loops we can use continue keyword to skip the remainder of the loop execution. How can we achieve something similar here.

Update:

i do not mean exactly on the first if() condition, if any of the if() condition is executed then what is best way of skipping the rest of the conditions like continue does in loop

like image 596
Jayy Avatar asked Nov 26 '22 20:11

Jayy


1 Answers

return fruit.weight <= 2 
    && "red".equals(fruit.color) 
    && "sweet".equals(fruit.taste)
    && fruit.isPerishable;
like image 60
Amit Deshpande Avatar answered Nov 29 '22 09:11

Amit Deshpande