Flow Control Statements in Java are essential for guiding how a program runs based on conditions or repeated actions. Whether you’re new to Java or brushing up on your skills, understanding these statements is crucial for writing clear and logical code. Let’s explore decision-making, looping, and jumping statements to see how they help manage the flow of a program effectively.
Flow Control Statements in Java
What are Flow Control Statements?
These are the statements that control the flow of the execution of a program. Flow control statements are essential programming tools that help manage the execution flow of your Java program. They dictate the sequence in which various statements, instructions, or function calls are carried out. With these statements, you can:
- Make decisions based on specific conditions
- Repeat code blocks multiple times
- Navigate to different sections of the program
- Effectively manage complex program logic.
There are three ways to control flow, by using.
Conditional/Decision-Making Statements
Decision-making statements in Java allow you to control the flow of program execution based on certain conditions. These statements enable your program to make decisions and execute different blocks of code accordingly.
Types of Conditional/Decision-Making Statements
There are five types of Decision-Making Statements:
- if Statement
- If else Statement
- If-else-if ladder Statement
- Nested if Statement
- Switch Statement
1. If Statement
- It is a Conditional/Decision-making statement and it controls the flow based on the condition.
- The if statement is the most basic decision-making statement. It executes a block of code only if the specified condition is true.
- if comes with a condition and it is associated with a true statement block (TSB).
- True statement block (TSB) will store the statements that should be executed whenever the condition is true.
Syntax:
if (Condition) {
//Statements
}
//next line
JavaExample:
public class Student {
public static void main(String[] args) {
int age = 20;
if (age >= 18) {
System.out.println("You are eligible to vote.");
}
}
}
Explanation:
- The condition age >= 18 is checked.
- Since the value of age is 20, which is greater than 18, the condition evaluates to true.
- The message “You are eligible to vote.” is printed.
- If the age had been less than 18, the code inside the if block would have been skipped.
2. If-else Statement
- It is a Conditional/Decision-making statement that controls the flow of execution of the program.
- The if-else statement provides an alternative action if the condition is false.
- The if comes with a condition and the condition is associated with a True statement block (TSB), else comes with a False statement block (FSB).
- In true statement block (TSB) we need to store the instructions that are exhibited whenever the condition is true.
- In a false statement block (FSB) we need to store the instructions that are executed whenever the condition is false.
Syntax:
if (Condition) {
//Statements
}else{
//Statements
}
//next line
JavaExample:
public class Student {
public static void main(String[] args) {
int age = 16;
if (age >= 18) {
System.out.println("You are eligible to vote.");
} else {
System.out.println("You are not eligible to vote.");
}
}
}
Explanation:
- The condition age >= 18 is checked.
- Since the age is 16, the condition evaluates to false.
- The code inside the else block is executed, printing “You are not eligible to vote.”
- This ensures that either the if block or the else block is executed, but not both.
3. if-else-if Ladder Statement
- It is a Conditional/Decision-making statement that controls the flow of execution of the program.
- The if comes with a condition and the condition is associated with the True statement block (TSB 1), else if comes with multiple conditions and each condition is associated with its own task (TSB).
- If any one of the conditions is true then it executes its True Statement Block (TSB) and the JVM goes to the next line (skips the next conditions).
- If all the conditions are false then the else block will execute, here the else block is not mandatory.
Syntax:
if (Condition 1) {
//Statements
}else if (Condition 2){
//Statements
}else if (Condition 3){
//Statements
}
.
.
.
else if (Condition n){
//statements when all the above condition are false and condition n is true
}else{
//statements when all the above condition are false
}
//next line
JavaExample:
public class Student {
public static void main(String[] args) {
int marks = 65;
if (marks > = 90) {
System.out.println("Grade: O");
} else if (marks >= 75) {
System.out.println("Grade: A");
} else if (marks >= 60) {
System.out.println("Grade: B");
} else {
System.out.println("Grade: C");
}
}
}
Explanation:
- The program checks the first condition, marks >= 90. It evaluates to false since 65 < 90.
- It then checks the second condition, marks >= 75, It evaluates to false since 65 < 75.
- It then checks the third condition, marks >= 60, which evaluates to true.
- The message “Grade: B” is printed.
- The remaining else block is skipped because one condition has already been satisfied.
- The if-else-if ladder helps simplify situations where you need to test several conditions in sequence.
4. Nested-if Statement
- It is a Conditional/Decision-making statement that controls the flow of execution of the program.
- You can place an if statement inside another if statement to create nested conditions.
- It’s used when you need to check a condition only after another condition is true.
Syntax:
if (Condition) {
if (Condition){
//Statements
}
}else{
//Statements
}
}else {
if (Condition){
//Statements
}
}else{
//Statements
}
}
//next line
JavaExample:
public class NestedIfExample {
public static void main(String[] args) {
int number = 15;
if (number > 0) {
if (number % 2 == 0) {
System.out.println("The number is +ve and even.");
} else {
System.out.println("The number is +ve but odd.");
}
} else {
if (number < 0) {
System.out.println("The number is -ve.");
} else {
System.out.println("The number is zero.");
}
}
}
}
Explanation:
- Outer if (number > 0)
- Check if the number is greater than 0 (positive).
- If true, the program evaluates the inner if (number % 2 == 0) condition.
- If false, the program moves to the outer else block.
- Inner if (number % 2 == 0) in Outer if Block
- Executes only if number > 0 is true and the number is divisible by 2 (even).
- Prints: “The number is positive and even.”
- Inner else in Outer if Block
- Executes only if number > 0 is true but the number is not divisible by 2 (odd).
- Prints: “The number is positive but odd.”
- Outer else Block
- Executes if number <= 0.
- Inside this block:
- Inner if (number < 0): Handles cases where the number is negative.
- Prints: “The number is negative.”
- Inner else: Handles cases where the number is zero.
- Prints: “The number is zero.”
- Inner if (number < 0): Handles cases where the number is negative.
5. Switch Statement
- It is a Conditional/Decision-making statement that controls the flow of execution of the program.
- The switch statement is a more readable way to check a variable against multiple fixed values, it is mainly used for multiple comparisons. The switch statement allows you to select one of many code blocks to be executed based on a value.
- In this Expression/Variable types and the case type should be the same.
- No case data should be repeated once again.
- If the variable/Expression didn’t match any case, the default block would execute.
Syntax:
switch (Variable/Expression) {
case condition 1:
//Statements
break;
case condition 2:
//Statements
break;
.
.
.
case condition n:
//Statements
break;
default;
//Statements
}
//next line
JavaExample:
public class Student {
public static void main(String[] args) {
int day = 3;
switch (day) {
case 1:
System.out.println("Monday");
break;
case 2:
System.out.println("Tuesday");
break;
case 3:
System.out.println("Wednesday");
break;
default:
System.out.println("Invalid day");
}
}
}
Explanation:
- The value of the day is 3.
- The program matches this value with case 3 and executes the corresponding block, printing “Wednesday”.
- The break statement prevents execution from continuing to the next cases.
- If the value of the day didn’t match any case, the default block would execute, printing “Invalid day”.
Looping Statements
Loops are one of the coolest tools in programming! They allow you to execute a block of code repeatedly as long as a specified condition is true. Loops save time, reduce redundancy, and make your code clean and efficient.
Types of Looping Statements in Java
Java provides three main types of looping statements:
- For loop
- While loop
- Do while loop
1. For Loop
- The for loop provides a more compact way to write loop structures that need to be executed a specific number of times.
- Think of the for loop as your go-to choice when you know exactly how many times you want to repeat a task.
- For comes with three properties in its syntax.
- Initialization of a variable
- The condition will be built with the help of the initialization variable.
- Increment/decrement of the initialization variable.
Syntax:
for (initialization; condition; increment/decrement) {
// Statements to execute
}
JavaExample:
Let’s print “Hello, World!” five times:
public class ForLoopExample {
public static void main(String[] args) {
for (int i = 1; i < = 5; i++) {
System.out.println("Hello, World! - " + i);
}
}
}
Explanation:
- The loop starts with int i = 1 (initialization).
- It checks if i <= 5 (condition). If true, it runs the code inside the loop.
- After each execution, i++ increases i by 1 (update).
Output:
Hello, World! - 1
Hello, World! - 2
Hello, World! - 3
Hello, World! - 4
Hello, World! - 5
2. While Loop
- The while loop is great when you’re unsure how many times you need to repeat the task, it keeps going until a condition is no longer true.
- The while loop executes a block of code as long as the specified condition remains true.
- The while comes with a condition and is associated with True Statement Block (TSB), while will execute the TSB until the condition remains true.
Syntax:
while (condition) {
// Statements to execute
}
JavaExample:
Imagine you want to keep printing numbers as long as they’re less than 5:
public class WhileLoopExample {
public static void main(String[] args) {
int count = 1;
while (count < 5) {
System.out.println("Count: " + count);
count++;
}
}
}
Explanation:
- The loop checks if count < 5 (condition).
- If true, it prints the value of the count and then increments the count by 1.
- At a count of 5, the loop will not execute because the condition is false, So JVM comes out of the while loop.
Output:
Count: 1
Count: 2
Count: 3
Count: 4
3. Do-While Loop
- The do-while loop is similar to the while loop, but it executes the code block at least once before checking the condition.
- The do-while loop is like a dare, it will execute the code at least once, even if the condition is false.
Syntax:
do {
// Statements to execute
} while (condition);
JavaExample:
Let’s print numbers from 1 to 3 using a do-while loop:
public class DoWhileLoopExample {
public static void main(String[] args) {
int count = 1;
do {
System.out.println("Count: " + count);
count++;
} while (count < = 3);
}
}
Explanation:
- The do block runs first and prints the value of the count.
- Then it checks the condition (count <= 3).
- If the condition is true, it repeats the loop; otherwise, it stops.
Output:
Count: 1
Count: 2
Count: 3
Loop Type | When to Use | At Least One Execution? |
for | When the number of repetitions is known. | No |
while | When the condition decides repetitions. | No |
do-while | When you need at least one execution. | Yes |
Jumping Statements
Jumping statements are a type of control flow mechanism that allows you to transfer control from one part of the program to another. You can use them to break out of a loop, skip the current iteration, or exit a method entirely.
Types of Jumping Statements
Java provides three main jumping statements:
- break Statement
- continue Statement
- return Statement
1. Break Statement
- The break statement is like an emergency exit, it lets you break out of a loop or a switch statement when a certain condition is met.
- It stops the execution of the loop or switch and moves the program control to the next statement after the loop or switch.
Syntax:
break;
JavaExample:
Let’s say we want to find the first number divisible by 5 in a list of numbers, and once we find it, we stop searching:
public class BreakExample {
public static void main(String[] args) {
int[] numbers = {1, 3, 4, 6, 10, 15};
for (int num : numbers) {
if (num % 5 == 0) {
System.out.println("First number divisible by 5 is: " + num);
break; // Breaks the loop once the condition is met
}
}
}
}
Explanation:
- We loop through the array of numbers.
- When we find the first number divisible by 5 (in this case, 10), the break statement exits the loop immediately.
Output:
First number divisible by 5 is: 10
2. Continue Statement
- The continue statement is used to skip the current iteration of a loop and move on to the next iteration.
- It doesn’t stop the loop entirely but just tells it to skip to the next cycle.
Syntax:
continue;
JavaExample:
Let’s print all the numbers from 1 to 10 except for 5:
public class ContinueExample {
public static void main(String[] args) {
for (int i = 1; i <= 10; i++) {
if (i == 5) {
continue; // Skip the iteration when i is 5
}
System.out.println(i);
}
}
}
Explanation:
- The loop goes through numbers 1 to 10.
- When i equals 5, the continue statement is executed, skipping the rest of the loop body for that iteration and moving to the next iteration.
Output:
1
2
3
4
6
7
8
9
10
3. Return Statement
- The return statement is used to exit a method and optionally return a value.
- It stops the execution of the current method and transfers control to the calling method.
Syntax:
return;
//or, if you want to return a value:
return value;
JavaExample:
Let’s write a method that returns the square of a number, and exits as soon as we return the result:
public class ReturnExample {
public static void main(String[] args) {
System.out.println("Square of 5 is: " + square(5));
}
public static int square(int num) {
return num * num; // Exits the method and returns the square of the number
}
}
Explanation:
- We call the square() method with the number 5.
- The return statement exits the method and returns the result of num * num.
Output:
Square of 5 is: 25
When to Use Jumping Statements?
- Use a break when you want to exit a loop or switch once a specific condition is met (like stopping a search after finding the result).
- Use continue when you want to skip an iteration of a loop but keep the loop going (like skipping certain numbers in a sequence).
- Use return when you want to exit a method early, possibly returning a value (like returning the result of a calculation).
Summary
Flow control statements in Java can be divided into three primary categories:
Decision-Making Statements
These statements enable the program to make choices based on specific conditions:
- if statement: Runs a block of code when the condition is true.
- if-else statement: Executes one block if the condition is true; otherwise, it runs a different block.
- if-else-if ladder: Checks multiple conditions in sequence.
- nested if statement: Involves placing one if or if-else statement inside another.
- switch statement: Chooses a block of code to execute from several options based on a key value.
Looping Statements
These statements allow a block of code to be repeated as long as a condition holds true:
- for loop: Runs a block of code a predetermined number of times.
- while loop: Continues to execute as long as the condition is true.
- do-while loop: Functions like the while loop but guarantees that the block runs at least once.
Jumping Statements
These statements change the normal flow of execution:
- break: Terminates a loop or switch statement before it naturally concludes.
- continue: Bypasses the remaining code in the current iteration and proceeds to the next one.
- return: Exits from a function and can return a value if needed.
Grasping these statements will help you write logical, organized, and reusable code for various applications.
Must Read
Operators in Java
– Get to know the various operators in Java and how to use them in expressions.
Decision-Making Statements in Java
– Learn how to control the flow of your program using if, if-else, switch, and other decision-making constructs.
Looping Statements in Java
– Master the art of iteration with for, while, and do-while loops in Java.
Jumping Statements in Java
– Understand how to alter the flow of loops using break, continue, and return statements in Java.
FAQ’S
What are decision-making statements in Java?
Decision-making statements in Java help execute specific blocks of code based on conditions, such as if, if-else, and switch.
When should I use a switch statement instead of multiple if-else statements?
Use a switch when you have multiple possible values for a single variable. It’s more readable than a long chain of if-else.
Can we nest if statements in Java?
Yes, Java allows nesting if statements. It’s commonly used when you need to check multiple related conditions.
Why are decision-making statements important in Java?
They allow dynamic program flow, enabling your application to respond differently based on various inputs or conditions.
What is the purpose of looping statements in Java?
Looping statements let you execute a block of code repeatedly, saving time and reducing redundancy.
Which Java loop should I use: for, while, or d`o-while?
Use for for known iteration counts, while for unknown counts, and do-while when you need the block to execute at least once.
Can loops be nested in Java?
Yes, Java supports nested loops. They’re useful for multidimensional operations, such as matrix handling.
What happens if a loop condition is always true?
The loop becomes infinite and can crash your program unless you use control statements like break.
What are jumping statements in Java?
Jumping statements like break, continue, and return alter the flow of loops or functions in Java.
How does the break statement work in loops?
break immediately exits the loop or switch case, stopping further execution of that block.
Is the return statement only for functions in Java?
Yes, the return statement is used to exit a function and optionally return a value to the caller.
Can continue and break be used in nested loops?
Yes, they can. break exits the loop entirely, while continue skips to the next iteration of the current loop.