The Java compiler processes the code sequentially, starting from the top and moving downwards. The execution of statements in Java follows the sequence in which they are written. Nevertheless, Java offers control flow statements that enable programmers to manage the flow of execution in Java code. These statements are known as control flow statements and are crucial for regulating the progression of a Java program.
Types of Control Flow Statements
Java provides three types of control flow statements.
- Decision Making statements if statements switch statement
- Loop statements do while loop while loop for loop for-each loop
- Jump statements break statement continue statement
- if statements
- switch statement
- do while loop
- while loop
- for loop
- for-each loop
- break statement
- continue statement
Java Decision-Making statements
Decision-making statements in programming determine which block of code to run based on the evaluation of a Boolean expression. These statements control the flow of a program by assessing the condition provided. In Java, there are two main types of decision-making statements: the If statement and the switch statement.
1) If Statement
In Java, the "if" statement is used to evaluate a condition. The control of the program is diverted depending upon the specific condition. The condition of the If statement gives a Boolean value, either true or false. In Java, there are four types of if-statements given below.
- Simple if statement
- if-else statement
- if-else-if ladder
- Nested if-statement
Let's understand the if-statements one by one.
1.1) Simple if statement
The if statement is fundamental in Java's control flow. It assesses a Boolean expression and allows the program to execute a block of code when the expression is true.
Syntax:
Syntax of if statement is given below.
if(condition) {
statement 1; //executes when condition is true
}
Take a look at this example demonstrating the utilization of the if statement within Java code.
Example
public class Main {
public static void main(String[] args) {
int x = 10;
int y = 12;
if(x+y > 20) {
System.out.println("x + y is greater than 20");
}
}
}
Output:
x + y is greater than 20
1.2) if-else statement
The if-else statement is an enhancement of the if statement, incorporating an additional block of code known as the else block. The else block is triggered when the condition in the if block is determined to be false.
Syntax:
It has the following syntax:
if(condition) {
statement 1; //executes when condition is true
}
else{
statement 2; //executes when condition is false
}
Consider the following example.
Example
public class Main {
public static void main(String[] args) {
int x = 10;
int y = 12;
if(x+y < 10) {
System.out.println("x + y is less than 10");
} else {
System.out.println("x + y is greater than 20");
}
}
}
Output:
x + y is greater than 20
1.3) if-else-if ladder
The if-else-if statement consists of an initial if-statement followed by several else-if statements. Essentially, it forms a sequence of if-else statements that construct a decision tree, allowing the program to access a specific code block when a condition evaluates to true. Additionally, it is possible to include a concluding else statement at the end of this sequence.
Syntax:
Syntax of if-else-if statement is given below.
if(condition 1) {
statement 1; //executes when condition 1 is true
}
else if(condition 2) {
statement 2; //executes when condition 2 is true
}
else {
statement 2; //executes when all the conditions are false
}
Consider the following example.
Example
public class Main {
public static void main(String[] args) {
String city = "Delhi";
if(city == "Meerut") {
System.out.println("city is meerut");
}else if (city == "Noida") {
System.out.println("city is noida");
}else if(city == "Agra") {
System.out.println("city is agra");
}else {
System.out.println(city);
}
}
}
Output:
1.4) Nested if-statement
Within nested if-statements, an if statement has the capability to enclose either an additional if statement or an if-else statement within it.
Syntax:
Syntax of Nested if-statement is given below.
if(condition 1) {
statement 1; //executes when condition 1 is true
if(condition 2) {
statement 2; //executes when condition 2 is true
}
else{
statement 2; //executes when condition 2 is false
}
}
Consider the following example.
Example
public class Main {
public static void main(String[] args) {
String address = "Delhi, India";
if(address.endsWith("India")) {
if(address.contains("Meerut")) {
System.out.println("Your city is Meerut");
}else if(address.contains("Noida")) {
System.out.println("Your city is Noida");
}else {
System.out.println(address.split(",")[0]);
}
}else {
System.out.println("You are not living in India");
}
}
}
Output:
2) Switch Statement
Switch statements in Java offer a comparable functionality to if-else-if statements. Within a switch statement, there are various code blocks known as cases, with only one case being executed depending on the value of the switched variable. Switch statements provide a simpler alternative to if-else-if statements and contribute to the overall clarity of the program.
Points to be noted about switch statement:
- The case variables can be int, short, byte, char, or enumeration. String type is also supported since version 7 of Java
- Cases cannot be duplicate
- Default statement is executed when any of the case doesn't match the value of expression. It is optional.
- Break statement terminates the switch block when the condition is satisfied. It is optional, if not used, next case is executed.
- While using switch statements, we must notice that the case expression will be of the same type as the variable. However, it will also be a constant value.
Syntax:
Below is the syntax for implementing the switch statement.
switch (expression){
case value1:
statement1;
break;
.
.
.
case valueN:
statementN;
break;
default:
default statement;
}
To grasp the flow of the switch statement, let's examine the example provided below.
Example
public class Main {
public static void main(String[] args) {
int num = 2;
switch (num){
case 0:
System.out.println("number is 0");
break;
case 1:
System.out.println("number is 1");
break;
default:
System.out.println(num);
}
}
}
Output:
When working with switch statements, it is essential to consider that the case expression must match the variable's type and be a constant value. Switch statements allow the use of int, string, and Enum type variables only.
Java Loop Statements
In programming, there are instances where it is necessary to repeatedly run a block of code as long as a certain condition remains true. Loop statements are employed for this purpose, enabling the execution of a series of instructions in a repetitive manner based on a specific condition.
In Java, we have three types of loops that execute similarly. However, there are differences in their syntax and condition checking time.
- Java for loop
- Java for-each loop
- Java while loop
- Java do-while loop
Let's understand the loop statements one by one.
Java for loop
In Java, the for loop bears resemblance to that of C and C++. It allows us to set the loop variable, validate the condition, and increment or decrement within a single line of code. The for loop is employed when the precise number of times the code block needs to be executed is known.
Syntax:
It has the following syntax:
for(initialization, condition, increment/decrement) {
//block of statements
}
The flow chart for the for-loop is given below.
To grasp the correct operation of the for loop in Java, let's examine the example provided below.
Example
public class Main {
public static void main(String[] args) {
// TODO Auto-generated method stub
int sum = 0;
for(int j = 1; j<=10; j++) {
sum = sum + j;
}
System.out.println("The sum of first 10 natural numbers is " + sum);
}
}
Output:
The sum of first 10 natural numbers is 55
Java for-each loop
Java offers an improved for loop for iterating through data structures such as arrays or collections. The for-each loop eliminates the need to manually update the loop variable.
Syntax:
Below is the syntax for utilizing the for-each loop in Java.
for(data_type var : array_name/collection_name){
//statements
}
To grasp how the for-each loop operates in Java, let's examine the following example.
Example
public class Main {
public static void main(String[] args) {
String[] names = {"Java","C","C++","Python","JavaScript"};
System.out.println("Printing the content of the array names:");
for(String name:names) {
System.out.println(name);
}
}
}
Output:
Printing the content of the array names:
Java
C
C++
Python
JavaScript
Java while loop
The while loop is utilized for iterating through multiple statements repeatedly. In cases where the number of iterations is unknown beforehand, the while loop is preferred. In contrast to the for loop, the initialization and increment/decrement operations are not contained within the while loop statement.
Referred to as the entry-controlled loop, this type of loop checks the condition at the beginning. When the condition is true, the loop body is executed; otherwise, the statements following the loop are executed.
Syntax:
The syntax of the while loop is given below.
while(condition){
//looping statements
}
The while loop's flowchart is illustrated in the image provided below.
Consider the following example.
Example
public class Main {
public static void main(String[] args) {
int i = 0;
System.out.println("Printing the list of first 10 even numbers");
while(i<=10) {
System.out.println(i);
i = i + 2;
}
}
}
Output:
Printing the list of first 10 even numbers
0
2
4
6
8
10
Java do-while loop
The do-while loop evaluates the condition at the end of the loop iteration, ensuring that the loop statements are executed at least once, especially when the iteration count is uncertain.
The do-while loop is sometimes referred to as the exit-controlled loop because the condition is evaluated after the loop body. Below is the syntax of the do-while loop.
do
{
//statements
} while (condition);
The diagram illustrating the flow of a do-while loop can be found in the image below.
To grasp how the do-while loop operates in Java, let's examine the example provided below.
Example
public class Main {
public static void main(String[] args) {
int i = 0;
System.out.println("Printing the list of first 10 even numbers ");
do {
System.out.println(i);
i = i + 2;
}while(i<=10);
}
}
Output:
Printing the list of first 10 even numbers
0
2
4
6
8
10
Java Jump Statements
Jump statements are utilized to redirect the flow of a program to particular statements. Essentially, they shift the control of execution to a different section of the program. In Java, there are two categories of jump statements which include:
- Java break statement
- Java continue statement
Java break statement
The break statement, as its name implies, is employed to disrupt the current program flow and shift control to the subsequent statement outside of a loop or switch statement. It should be noted that in the scenario of nested loops, the break statement only disrupts the inner loop, leaving the outer loop unaffected.
In Java, the break statement is not allowed to stand alone, meaning it must be contained within a loop or switch statement to function properly.
The break statement example with for loop
Take a look at this example demonstrating the utilization of the break statement in conjunction with a for loop.
Example
public class Main {
public static void main(String[] args) {
for(int i = 0; i<= 10; i++) {
System.out.println(i);
if(i==6) {
break;
}
}
}
}
Output:
0
1
2
3
4
5
6
break statement example with labeled for loop
Example
public class Main {
public static void main(String[] args) {
a:
for(int i = 0; i<= 10; i++) {
b:
for(int j = 0; j<=15;j++) {
c:
for (int k = 0; k<=20; k++) {
System.out.println(k);
if(k==5) {
break a;
}
}
}
}
}
}
Output:
0
1
2
3
4
5
Java continue statement
In contrast to the break statement, the continue statement does not terminate the loop. Instead, it bypasses a particular section of the loop and proceeds to the next iteration without delay.
To grasp how the continue statement operates in Java, let's examine the example below.
Example
public class Main {
public static void main(String[] args) {
for(int i = 0; i<= 2; i++) {
for (int j = i; j<=5; j++) {
if(j == 4) {
continue;
}
System.out.println(j);
}
}
}
}
Output:
0
1
2
3
5
1
2
3
5
2
3
5