Control Flow in Java
In the previous blog, we learned about Input and Output in Java. If you want to know more about it, visit the Input and Output in Java. In this blog, we will learn about Control Flow in Java. In Java, code executes in sequential order(top to bottom). The statements in the code are executed in the order that the code/program appears. In order to control the flow of Java code, some statements are provided, such statements are called Control Flow Statements. To determine the control flow of code, Java provides control statements and loops.
Block Scope
Blocks consist of a number of Java statements that are enclosed within the pair of curly braces. Variables are defined in the block and the scope of variables is within the block. There can be blocks inside the other blocks that are called nested blocks.
e.g
We cannot declare the same variables within the two nested blocks. If we do so, then we will get an error saying cannot redefine the variable in the inner block.
e.g
Control Statements
The conditional statement has the following syntax:
The condition should be surrounded by the parenthesis(( )). Just like in other languages, in Java, we can execute multiple statements when the condition is true. In order to execute multiple statements, we use block statements. It has the following syntax:
Syntax
In order to check the conditions, control statements are used. The following are the control statements:
if statement
if statement is used to check the condition. If the condition satisfies, then the if statement is executed, but if the condition does not satisfy, then the if statement is not executed. The syntax is:
Syntax
Flowchart
e.g
Output
if-else statement
if-else statement is used for testing the condition. If the condition in the if block satisfies, then it executes the if statement, otherwise executes the else statement. if-else has the following syntax:
Syntax
In the if-else statement the else part is not mandatory(optional). An else statement groups with the if, which is nearest to it.
Flowchart
e.g
Output
if-else if Statement
if-else if statement is used for executing one block of code among the multiple blocks. The general syntax is:
Syntax
Flowchart
e.g
Output