Flow Control Statements Syntaxes and Example in Java
The flow of execution of a normal program happens in a sequential order that means from top to bottom one by one statement at a time. In programming there are some situations where you need to change this execution order.
Consider if you want to execute a block of statements only if a particular condition satisfies or if you want to execute a block of statements n number of times repetitively, this is possible with control statements. By using control statements in Java you can control the flow of program execution.
There are many control statements in Java, those are broadly categorised in below three types.
Types of control statements in Java:
- Branching / Decision Making Statements.
- Loops / Iteration / Repetition Statements.
- Jumping / Transfer Statements.
Branching / Decision Making Statements
If you do not want to execute all the statements in a program, instead some statements must be executed if and only if a condition satisfies or becomes true, and if a variable gets an expected value. To execute group of statements depending on a condition you will require decision making statements.
Example: If you want to find even numbers or you have to execute block of statements depend on user input then you will require decision making statements in java program.
Following are the types of decision making statements:
- If else
View more details here.
- Switch Case
View more details here.
Note: The ternary operator b?stmt1: stmt2; can be used for decision making but ternary operator is an operator and not the control statement.
Looping Statements
If you want to execute one or more statements repetitively for fix number of iteration or for infinite time then you need to use looping statements. The looping statements are also called iteration statements or repetitive statements.
Example: If you have to print 1 to 1000 numbers, or you have to do addition of 1 to 500 numbers, or insert values into the array or list then you will require looping statements.
Following are the types of looping statements in Java.
- For and For Each Statements
View more details here.
- While and Do While Statements
View more details here.
Jumping Statements
The jumping statements in Java can transfer the flow of program execution to a particular line or outside the current loop.
Example: Consider you have to skip some loop iterations or you have to stop the execution of the current loop or you have start the execution of statements on a particular line then you need to use jumping statements.
Following are the jumping statements in Java:
- Break Statement
View more details here.
- Continue Jumping Statement
View more details here.
- Goto Statement(Not supported in Java)
- Return Statement
View more details here.