Two-Way if-else Statements:
An if-else statement allows a program to choose between two different execution paths based on whether a condition is true or false.
While a one-way if statement performs an action only when the specified condition is true, a two-way if-else statement provides alternative actions to be taken depending on whether the condition is true or false.
The syntax for a two-way if-else statement is as follows:
- if (boolean-expression) {
- statement(s)-for-the-true-case;
- }
- else {
- statement(s)-for-the-false-case;
- }
The flowchart of this statement is depicted in Figure -1.
Figure-1 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 is executed. If it evaluates to false, the statement(s) for the false case is executed.
For instance, 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");
- }
If the condition `radius >= 0` is true, the area is computed and displayed. If it is false, the message "Negative input" is displayed.
Braces enclosing the statements within the if and else blocks can be omitted if there is only one statement within each block.
Here is another example using the if-else statement. The code checks whether a number is even or odd:
- if (number % 2 == 0)
- System.out.println(number + " is even.");
- else
- System.out.println(number + " is odd.");
If the condition `number % 2 == 0` is true, the number is considered even and the corresponding message is printed. Otherwise, if the condition is false, the number is considered odd and a different message is printed.
Comments
Post a Comment