Control Flow in Java
The sequence in which statements, instructions, or operations are executed in a program is known as control flow. Understanding control flow is essential for writing efficient, logical , robust and error free code.
In Java , compiler execute code from top to bottom. Java compiler execute code in the sequence in which they appears. Java provide some statement or instructions that control execution flow of java code. such statements are known as control flow statements. It is a fundamental feature of java and supported in other language also. You can write and manage your code execution flow more effectively with the help of these control flow statements.
Java provides three types of control flow statements
- Decision Making statements
- if statement
- switch statement
- looping statements
- for loop
- do while loop
- while loop
- for-each loop
- branching/Jump statements
- break statement
- continue statement
- return statement
Decision Making statements
As the name suggest , decision-making statements allow you to control the flow of code execution based on certain conditions. with the help of these type of control flow statements you can decide which statement to execute and when. you can control flow depending upon the result of the provided condition.
if statement
if( condition) { // code block }
if statement is used to control execution of a code block based on certain condition. if provided condition evaluates to true then program execution enter inside block of code. in Java , there are four types of if-statements.
- if statement
- if else statement
- if else if statement
- nested if statement
switch statement
switch statement is similar like if-else-if statement. switch statement contains multiple block of code called case. if the evaluated condition satisfied the case that case code block will execute if no case satisfied then default code block will execute. switch statement is better than if-else-if statement it enhances the readability of the program.
switch(condition) { case x: //code break; case y: // code break; default: // code }