DEV Community

Anees Abdul
Anees Abdul

Posted on

Control Flow Statement in Java:

In this article, we’ll explore control flow statements in Java, with simple explanations!
What is a Control Flow Statement:
In simple words, it controls the execution flow of a program. It decides which statement runs, how many times it runs, and when it stops.
Types of Control Flow Statement:

  1. Decision-Making Statement
  2. Looping Statement
  3. Jump Statement

1. What is a Decision-Making Statement?
It takes a decision based on the statement condition.

1.1 If Statement: It executes the code only if the condition is true. if is a java keyword.
Syntax:

if(condition){
//Code
}
Enter fullscreen mode Exit fullscreen mode

1.2 Else Statement: It executes the code only if the condition is false. else is a java keyword.
Syntax:

else(condition){
//code
}
Enter fullscreen mode Exit fullscreen mode

1.3 Else If Statement: It is used when the program needs to make multiple decisions. "else if" is always written after "if." else if is a java keyword.
Syntax:

else if(){
//code
}
Enter fullscreen mode Exit fullscreen mode


**
1.4 Switch Statement: It chooses one action from many options based on the value of a variable.
Syntax:

switch (expression) {
    case value1:
        // code to execute if expression == value1
        break;
    case value2:
        // code to execute if expression == value2
        break;
    // you can have any number of cases
    default:
        // code to execute if none of the cases match
}
Enter fullscreen mode Exit fullscreen mode

2. What is a Looping Statement:
It allows a program to execute a block of code repeatedly as long as a given condition is true. Instead of writing the same code multiple times, loops help make programs shorter, cleaner, and more efficient.

2.1 What is for Loop:
It is the replacement of the while loop statement, where it reduces the line of code by having initialization, condition, increment/decrement in a single line.
Syntax:

for (initialization; condition; update) {
    // code to be executed repeatedly
}
Enter fullscreen mode Exit fullscreen mode

2.2 What is While Loop:
It is the entry check loop, where it repeatedly runs a block of code as long as a condition is true. If the condition is false initially, the loop body won’t run even once.
Syntax:

while (condition) {  // Condition checked first
    System.out.println(i);  // This will run if the condition is true
    }
Enter fullscreen mode Exit fullscreen mode

Top comments (0)