Programming |
Control statements are used to control the flow of the program based on certain conditions. There can be situations like the user needs to run the same code multiple times or a few lines of code to be run only when a number is odd etc. These are various types of control statements in Java:
Conditional control statement: Conditional control statement is used to execute some statement(s) based on some condition. Examples of conditional statement are:
Syntax:
if (expression) {
Statement;
}
2. if-else statement : If the Boolean expression results in true then if block will execute. If the Boolean expression is false then the code inside else block will execute.
Syntax:
if (expression) {
Statement;
}else{
Statement;
}
3. Nested if statement: If there are more than one condition for a statement to be executed then nested if statement can be used.
Syntax:
if (expression) {
if (expression) {
Statement;
}
}else{
Statement;
}
4. if else ladder: This statement can be used when same value has to be compared with more than one condition.
Syntax:
if (expression) {
Statement
} else if (expression) {
Statement;
}else if(expression){
Statement;
}else {
Statement;
}
For e.g. we need to write code depending on days of a week. Writing that code using if else will be very tedious, confusing and less readable.
Syntax:
switch (expression) {
case 1: Statement
case 2: Statement
default: Statement
}
Rules of using switch statements
Looping/iteration control statement
This statement is used to execute a block of code multiple times based on some condition.
It is the most famous and widely used statement. It is used to loop a code for a number of times. All that code can be accommodated in one line.
Syntax:
for (initialization; condition; iteration){
statement;
}
You can initialize multiple variables in the initialization and iteration part of for statement.
While statement can be used when the number of times in not known to the user.
Syntax:
while (expression) {
statement;
}
do while is same as while statement but it will run atleast once.
Syntax:
do{
statement;
} while (expression);
Unconditional control statement
break is a keyword in java. It is used to terminate the execution of the current switch block or looping statement. Break statement can only be used within a switch or loop statement.
continue is also a keyword. It is used inside any looping statement. Continue statement can be used to skip some statement from the block of the looping statement.
In the case of for statement, the control will be transferred to the iteration statement. In the case of while or do-while the control will be transferred to the conditional statement.