The if-else statement
The if-else statement allows you to execute some code only if a certain condition is true, and other code if the condition is false. It is defined as this template:
if ( condition ) {
if-body
}
else {
else-body
}
where
- condition is a boolean expression;
- if-body is zero or more statements;
- else-body is zero or more statements;
- The if-else statement executes the code in if-body if and only if condition evaluates to true; otherwise, it executes the code in else-body.
The following code prints one message if the player guessed a the answer to a quiz question correctly and another message if they didn't.
if (playerAnswer == correctAnswer) {
System.out.println("Correct! Play again?");
} else {
System.out.println("Sorry, that isn't correct. Try again?");
}