Control Statements in Java
Control Statements in Java
Control Statements in Java is one of the fundamentals required for Java Programming. It
allows the smooth flow of a program. Following pointers will be covered in this article:
Simple if statement
if-else statement
Nested if statement
Switch statement
Looping statements
While
Do-while
For
For-Each
Branching statements
Break
Continue
Selection statements
Iteration statements
Jump statements
Simple if statement
The if statement determines whether a code should be executed based on the specified
condition.
Syntax:
if (condition) {
Statement 1; //executed if condition is true
}
Statement 2; //executed irrespective of the condition
Example:
Output:
Good day.
If..else statement
In this statement, if the condition specified is true, the if block is executed. Otherwise, the
Syntax:
if (condition1) {
Statement 1; //executed if condition is true
else {
Statement 2; //executed if condition is false
}
}
Example:
Output:
Good evening.
Nested if statement
An if present inside an if block is known as a nested if block. It is similar to an if..else
Syntax:
if (condition1) {
Statement 1; //executed if first condition is true
if (condition2) {
Statement 2; //executed if second condition is true
}
else {
Statement 3; //executed if second condition is false
}
}
Example:
Good evening.
While
Known as the most common loop, the while loop evaluates a certain condition. If the
condition is true, the code is executed. This process is continued until the specified
The condition to be specified in the while loop must be a Boolean expression. An error
Syntax:
while (condition)
{
statementOne;
}
Example:
Output:
0
1
2
3
4
Do..while
The do-while loop is similar to the while loop, the only difference being that the condition
in the do-while loop is evaluated after the execution of the loop body. This guarantees that
Syntax do{
: //code to be executed
}while(condition);
Example:
Output:
0
1
2
3
4
5
For
The for loop in java is used to iterate and evaluate a code multiple times. When the number
Syntax:
Output:
0
2
4
6
8
10
For-Each
The traversal of elements in an array can be done by the for-each loop. The elements
present in the array are returned one by one. It must be noted that the user does not
{
}
Example:
Output:
Oops
DPD
DS
CO
Switch Statement
Output:
Thursday
Simple if statement:
The if statement determines whether a code should be executed based on the specified
condition.
Syntax:
if (condition) {
}
Statement 2; //executed irrespective of the condition