Consider the following code segment. What is printed as a result of executing the code segment?
boolean ready = false;
int attempts = 2;
if (ready) {
attempts = attempts + 1;
} else {
attempts = attempts + 3;
}
System.out.println(attempts);
2536ready is false, the else branch runs and adds 3, so attempts becomes 5.
Explanation
An if/else statement contains two branches and executes exactly one of them. The condition here is the boolean variable ready, whose value is false, so the else branch runs and the if branch is skipped entirely.
- A is not correct: 2 is the starting value of
attempts, but anif/elsestatement always executes one of its two branches, so the value must change. - C is not correct: 3 is what the
ifbranch would produce, and that branch runs only whenreadyistrue, which it is not. - D is not correct: 6 comes from tracing both branches, but after one branch finishes, execution continues after the entire
if/elsestatement.