We have just covered if statements, but what if we want something to be done if the condition that we are checking is false? This is where the else statement comes into play. The header for the else does not have a condition and is just "else" while the body is what is performed if the condition for the if statement is false.
Together, these create an if-else statement, or a two-way selection. Here is the anatomy of an if-else statement:
some code that runs before conditional statement
if (condition) {
code that runs if the condition is true
} else {
code that runs if the condition is false
}
some code that runs after
Remember to place brackets around all of the code that should run if the condition is true and brackets around all of the code that should run if the condition is false. Without brackets, the computer may get confused about what code it should run and do something you're not expecting. You can prevent a lot of headaches by remembering to add brackets around each body and indenting the code inside!
Remember the rounding we learned in 1.5? Now with an if-else statement, we can finally write a method that implements this as follows:
public static int round(double number) {
if (number >= 0) {
return (int) (number + 0.5);
} else {
return (int) (number - 0.5);
}
}