UNIT-1 Control Structure
UNIT-1 Control Structure
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.
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.
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
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 is given below.
if(condition)
{
statement 1; //executes when condition is true
}
Consider the following example in which we have used the if statement in the java code.
Student.java
}
}
}
Output
x + y is greater than 40
2) if-else statement
The if-else statement is an extension to the if-statement, which uses another block of code, i.e., else block. The
else block is executed if the condition of the if-block is evaluated as false.
Syntax
if(condition)
{
statement 1; //executes when condition is true
}
else
{
statement 2; //executes when condition is false
}
Consider the following example.
Student.java
Output:
x + y is greater than 20
3) if-else-if ladder:
The if-else-if statement contains the if-statement followed by multiple else-if statements. In other words, we can
say that it is the chain of if-else statements that create a decision tree where the program may enter in the block
of code where the condition is true. We can also define an else statement at the end of the chain.
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
}
Student.java
public class Student
{
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:
Delhi
4. Nested if-statement
In nested if-statements, the if statement can contain a if or if-else statement inside another if or else-if statement.
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:
Delhi
Switch Statement:
In Java, Switch statements are similar to if-else-if statements. The switch statement contains multiple blocks of
code called cases and a single case is executed based on the variable which is being switched. The switch
statement is easier to use instead of if-else-if statements. It also enhances the readability of the program.
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
switch (expression)
{
case value1:
statement1;
break;
.
.
.
case valueN:
statementN;
break;
default:
default statement;
}
Consider the following example to understand the flow of the switch statement.
Student.java
// Java program to Demonstrate Switch Case
// with Primitive(int) Data Type
// Class
public class GFG
{
// Main driver method
public static void main(String[] args)
{
int day = 5;
String dayString;
// Case
case 1:
dayString = "Monday";
break;
// Case
case 2:
dayString = "Tuesday";
break;
// Case
case 3:
dayString = "Wednesday";
break;
// Case
case 4:
dayString = "Thursday";
break;
// Case
case 5:
dayString = "Friday";
break;
// Case
case 6:
dayString = "Saturday";
break;
// Case
case 7:
dayString = "Sunday";
break;
// Default case
default:
dayString = "Invalid day";
}
System.out.println(dayString);
}
}
Output
Friday
import java.util.Scanner;
public class Days
{
public static void main(String[] args)
{
Scanner nn = new Scanner(System.in);
int dayNum;
System.out.print("Enter a day number (1-7): ");
dayNum = nn.nextInt();
switch(dayNum)
{
case 1:
System.out.println("Monday");
break;
case 2:
System.out.println("Tuesday");
break;
case 3:
System.out.println("Wednesday");
break;
case 4:
System.out.println("Thursday");
break;
case 5:
System.out.println("Friday");
break;
case 6:
System.out.println("Saturday");
break;
case 7:
System.out.println("Sunday");
break;
default:
System.out.println("Invalid day number.");
break;
}
}
}
Output:
Enter a day number (1-7): 6
Saturday
Enums
An enum is a special "class" that represents a group of constants (unchangeable variables, like final variables).
To create an enum, use the enum keyword (instead of class or interface), and separate the constants with a
comma. Note that they should be in uppercase letters:
Example:
enum Level
{
LOW,
MEDIUM,
HIGH
}
An enum cannot be used to create objects, and it cannot extend other classes (but it can implement interfaces).
Example:
public class MainEnum
{
enum Level
{
LOW,
MEDIUM,
HIGH
}
Output:
Medium
Example
enum Level
{
LOW,
MEDIUM,
HIGH
}
switch(myVar) {
case LOW:
System.out.println("Low level");
break;
case MEDIUM:
System.out.println("Medium level");
break;
case HIGH:
System.out.println("High level");
break;
}
}
}
Output:
Medium level
Example:
for (Level myVar : Level.values())
{
System.out.println(myVar);
}
Output:
LOW
MEDIUM
HIGH
Loop Statements
In programming, sometimes we need to execute the block of code repeatedly while some condition evaluates to
true. However, loop statements are used to execute the set of instructions in a repeated order. The execution of
the set of instructions depends upon a particular condition.
In Java, we have three types of loops that execute similarly. However, there are differences in their syntax and
condition checking time.
for loop
while loop
do-while loop
for-each loop
Consider the following example to understand the proper functioning of the for loop in java.
Calculation.java
Output:
The sum of first 10 natural numbers is 55
For-each loop
The for-each loop in Java (also called the enhanced for loop) was introduced in Java 5 to simplify iteration over
arrays and collections. It is cleaner and more readable than the traditional for loop and is commonly used when
the exact index of an element is not required.
Below is a basic example of using the for-each loop to iterate through an array and print each element. A for-
each loop directly accesses elements without needing index variables.
Syntax
for(new variable:array)
{
//Statement ;
}
Example:
// Java Program to Iterate through an array
// Using for-each loop
import java.io.*;
class ForEach {
Output:
12345
Example:
public class Language
{
public static void main(String[] args)
{
String[] names = {"Java","C","C++","Python","JavaScript"};
System.out.println("Printing the content of the array names:\n");
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 also used to iterate over the number of statements multiple times. However, if we don't know
the number of iterations in advance, it is recommended to use a while loop. Unlike for loop, the initialization
and increment/decrement doesn't take place inside the loop statement in while loop.
It is also known as the entry-controlled loop since the condition is checked at the start of the loop. If the
condition is true, then the loop body will be executed; otherwise, the statements after the loop will be executed.
Calculation .java
Output:
Printing the list of first 10 even numbers
0
2
4
6
8
10
It is also known as the exit-controlled loop since the condition is not checked in advance. The syntax of the do-
while loop is given below.
do
{
//statements
} while (condition);
Calculation.java
Output:
Printing the list of first 10 even numbers
0
2
4
6
8
10
Jump Statements
Jump statements are used to transfer the control of the program to the specific statements. In other words, jump
statements transfer the execution control to the other part of the program. There are two types of jump
statements in Java, i.e., break and continue.
The break statement cannot be used independently in the Java program, i.e., it can only be written inside the
loop or switch statement.
Consider the following example in which we have used the break statement with the for loop.
BreakExample.java
public class BreakExample
{
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
Output:
0
1
2
3
5
1
2
3
5
2
3
5