Java ch4
Java ch4
Chapter Four
Java Control Statements
Overview
Java compiler executes the code from top to bottom. The statements in the code are executed according to the
order in which they appear. However, Java provides statements that can be used to control the flow of Java code.
Such statements are called control flow statements. It is one of the fundamental features of Java, which provides
a smooth flow of program.
Java provides three types of control flow statements.
1. Decision Making statements
o if statements, switch statement
2. Loop statements
o do while loop, while loop, for loop, for-each loop
3. Jump statements
o break statement, continue statement
1. Decision-Making statements: As the name suggests, decision-making statements decide which statement to
execute and when. Decision-making statements evaluate the Boolean expression and control the program
flow depending upon the result of the condition provided. There are two types of decision-making statements
in Java, i.e., If statement and switch statement.
a) 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) Simple if statement: It is the most basic statement among all control flow statements in Java. It evaluates
a Boolean expression and enables the program to enter a block of code if the expression evaluates to
true.
Syntax of if statement
if(condition) {
statement 1; //executes when condition is true
}
Consider the following example in which we have used if statement in the java code.
Student.java
Class Name Student.java
public class Student {
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
Consider the following example to understand the proper functioning of the for loop in java.
Calculation.java
public class Calculation {
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 provides an enhanced for loop to traverse the data structures like array or collection. In the for-each loop, we
don't need to update the loop variable. The syntax to use the for-each loop in java is given below.
for(data_type var : array_name/collection_name){
//statements
}
Consider the following example to understand the functioning of the for-each loop in Java.
The flow chart for the while loop is given in the following image.