A program normally executes from top to bottom except when we use control statements, we can control the order of execution of the program, based on logic and values.
In Java, control statements can be divided into the following three categories:
1- Selection or conditional statements :
Selection statements allows us to control the flow of program execution on the basis of the outcome of an expression :
(if , if - else , if - else - if , nested if-else , switch)
if :
if statement is the most simple decision making statement. It is used to decide whether a certain statement or block of statements will be executed or not i.e if a certain condition is true then a block of statement is executed otherwise not.
You can try examples here .
if-else :
The if statement alone tells us that if a condition is true it will execute a block of statements and if the condition is false it won’t. But what if we want to do something else if the condition is false. Here comes the else statement. We can use the else statement with if statement to execute a block of code when the condition is false.
You can try examples here .
if-else-if :
Here, a user can decide among multiple options. The if statements are executed from the top 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.
You can try examples here .
nested if-else :
in nested if-else we can use one if statement inside another if or else if statement .
switch :
The switch statement is a multi-way branch statement . It defines multiple paths of execution of a program . It provides a better alternative than a large series of if-else-if statement .
You can try examples here .
Top comments (0)