If branches & execution

If in the middle of execution of an if branch the condition ceases to be true, will Java stop running that if, even if there’s more code to execute? For example (imagine, it’s part of a String method)

boolean returnedSthElse;

[...]

if((int)(Math.random() * 2) == 1 && !returnedSthElse){
        returnedSthElse = true;
        return "Something else";
} else {
         return "Something";
}

Suppose the random int is 1, and the process continues through the first if branch. After returnedSthElse is true, will it proceed to return “Something else”, or would it be like, “Oh, sh*t, it’s no longer the right branch, I’d better quit it now” and fail to return it?

Java would not stop running that if-block if the condition changes inside the block.

1 Like

Thank you! Then, I’ll have to continue looking for what causes a logical error in my code…