If-else construct
Last updated
Last updated
Java supports two selection statements:
If
switch.
These statements allow you to control the flow of your program’s execution based upon conditions known only during run time.
An if construct enables you to execute code based on certain conditions.Output of these conditions should be a boolean value.
Flavors of If:
When you run the program, the output will be:
The output from this program is:
If the condition is true, then statement1 is executed. Otherwise, statement2 (if it exists) is executed.
In no case will both statements be executed.
Here, if a is less than b, then a is set to zero. Otherwise, b is set to zero
A) II. Nested ifs:
A nested if is an if statement that is the target of another if or else.
When you nest ifs, the main thing to remember is that an else statement always refers to the nearest if statement that is within the same block as the else and that is not already associated with an else.
Here, as the comments indicate, the final else is not associated with if(j<20) because it is not in the same block (even though it is the nearest if without an else).
Rather, the final else is associated with if(i==10).
The inner else refers to if(k>100) because it is the closest if within the same block.
A) III. if-else-if Ladder:
A common programming construct that is based upon a sequence of nested ifs is the if-else-if ladder.
Syntax:
Here 'if' statements are executed from top to down.
As soon as one of the conditions controlling the 'if' is true, the statement associated with that if is executed, and the rest of the ladder is bypassed.
If none of the conditions is true, then the final else statement will be executed.
The final else acts as a default condition; that is, if all other conditional tests fail, then the last else statement is performed.
If there is no final else and all other conditions are false, then no action will take place.
Example: Demonstrate if-else-if statements.
Output:
April is in the Spring.