Java Flow Control
Learn about Flow Control in Java. Understand how to control the execution flow of your program using decision-making, looping, and branching statements.
In Java, the execution of code typically happens from top to bottom, line by line. However, simply executing lines sequentially is not enough for complex logic. We need to make decisions, repeat tasks, or jump to different parts of the code. This is where Flow Control comes in.
Flow Control statements allow you to control the order in which the statements in your program are executed.
Types of Flow Control
There are three main types of flow control statements in Java:
- Decision-Making Statements (Selection)
- Looping Statements (Iteration)
- Branching Statements (Jump)
graph TD
A[Flow Control] --> B[Decision Making]
A --> C[Looping]
A --> D[Branching]
B --> B1[if-else]
B --> B2[switch]
C --> C1[for loop]
C --> C2[while loop]
C --> C3[do-while loop]
C --> C4[for-each loop]
D --> D1[break]
D --> D2[continue]
D --> D3[return]
style A fill:#f9f,stroke:#333,stroke-width:2px1. Decision-Making Statements 🚦
These statements allow your program to choose between different paths of execution based on certain conditions.
- if...else Statement: Executes a block of code if a condition is true, and another block if it's false.
- switch Statement: Selects one of many code blocks to be executed.
2. Looping Statements 🔄
These statements allow you to execute a block of code repeatedly.
- for Loop: Used when you know exactly how many times you want to loop.
- Enhanced for Loop: Used to iterate through elements of arrays and collections.
- while Loop: Loops through a block of code as long as a specified condition is true.
- do...while Loop: Similar to
while, but guarantees the code block is executed at least once.
3. Branching Statements ⤵️
These statements allow you to transfer control to another part of your program.
- break Statement: Terminates the loop or switch statement.
- continue Statement: Skips the current iteration of a loop and proceeds to the next one.
- return Statement: Exits from the current method.
Tip 💡: Mastering flow control is essential for writing logic. Without it, your program is just a static list of instructions!
Which type of flow control statement is used to repeat a block of code?
Challenge
Challenge
Task:
What is the output of this code snippet?Java Expressions, Statements and Blocks
In this tutorial, you will learn about Java expressions, Java statements, difference between expression and statement, and Java blocks with the help of examples.
Java if...else Statement
In this tutorial, you will learn about control flow statements using Java if and if...else statements with the help of examples.
