Selection statements: if, if-else and switch. · Loop statements: while, do-while and for.
· Transfer statements: break, continue, return, try-catch-finally and assert.
We use control statements when we want to change the default sequential order of execution
Selection Statements
The If Statement
The if statement executes a block of code only if the specified expression is true. If the value is false, then the if block is skipped and execution continues with the rest of the program. You can either have a single statement or a block of code within an if statement. Note that the conditional expression must be a Boolean expression.
The simple if statement has the following syntax:
if (
Below is an example that demonstrates conditional execution based on if statement condition.
public class IfStatementDemo { |
Output
b > a
The If-else Statement
The if/else statement is an extension of the if statement. If the statements in the if statement fails, the statements in the else block are executed. You can either have a single statement or a block of code within if-else blocks. Note that the conditional expression must be a Boolean expression.
The if-else statement has the following syntax:
if (
else
Below is an example that demonstrates conditional execution based on if else statement condition.
public class IfElseStatementDemo { |
Output
b > a
Its general form is as follows:
switch (
case label1:
case label2:
…
case labeln:
default:
} // end switch
When executing a switch statement, the program falls through to the next case. Therefore, if you want to exit in the middle of the switch statement code block, you must insert a break statement, which causes the program to continue executing after the current code block.
Below is a java example that demonstrates conditional execution based on nested if else statement condition to find the greatest of 3 numbers.
public class SwitchCaseStatementDemo {
|
Output
c is the greatest