DEV Community

Cover image for Two-Way if-else Statements
Paul Ngugi
Paul Ngugi

Posted on

Two-Way if-else Statements

An if-else statement decides the execution path based on whether the condition is true or false. A one-way if statement performs an action if the specified condition is true. If the condition is false, nothing is done. But what if you want to take alternative actions when the condition is false? You can use a two-way if-else statement. The actions that a two-way if-else statement specifies differ based on whether the condition is true or false. Here is the syntax for a two-way if-else statement:

if (boolean-expression) {
 statement(s)-for-the-true-case;
}
else {
 statement(s)-for-the-false-case;
}
Enter fullscreen mode Exit fullscreen mode

The flowchart of the statement is shown below:

Image description

An if-else statement executes statements for the true case if the Boolean-expression evaluates to true; otherwise, statements for the false case are executed.

If the boolean-expression evaluates to true, the statement(s) for the true case are executed; otherwise, the statement(s) for the false case are executed. For example, consider the following code:

if (radius >= 0) {
 area = radius * radius * PI;
 System.out.println("The area for the circle of radius " +
 radius + " is " + area);
}
else {
 System.out.println("Negative input");
}
Enter fullscreen mode Exit fullscreen mode

If radius >= 0 is true, area is computed and displayed; if it is false, the message "Negative input" is displayed. As usual, the braces can be omitted if there is only one statement within them. The braces enclosing the System.out.println("Negative input") statement can therefore be omitted in the preceding example. Here is another example of using the if-else statement. The example checks whether a number is even or odd, as follows:

if (number % 2 == 0)
 System.out.println(number + " is even.");
else
 System.out.println(number + " is odd.");

Enter fullscreen mode Exit fullscreen mode

Top comments (0)