简体   繁体   中英

Java: Can the if/else statement be used with a 'return true' and a 'return false'

public boolean ifElseStatement(){

    if(conditions){
       statementBody++;
       return true;
    }
       else
       return false;

If the condition is met, will this method return true ? Or might it return false because it the final return statement is outside of the if body?

I am effectively asking is this correct use of the if/else statement when a boolean value needs to be returned? Or perhaps there is a better or universally preferred way to do this?

To clarify, I am asking if the if-else statement can be used like this, with two return statements. I have always been told to use only one return statement.

If the condition is true, it will not be able to hit the return of the else statement. Once it hits a return, your code immediately returns to where the ifElseStatement() was invoked. Returning a Value from a Method

The method will return the first return statement reached. If conditions == true, will return true, in other case, will return false.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM