Control Statements
[Link] AP/CSE
Control Statements
Programming language uses control statements to cause the
flow of execution to advance and branch based on changes to
the state of a program.
Java’s program control statements can be put into the following
categories:
selection, iteration, and jump.
Decision Making statements
◦ if statements
◦ switch statement
Loop statements
◦ do while loop
◦ while loop
◦ for loop
◦ for-each loop
Jump statements
◦ break statement
◦ continue statement
Java’s Selection Statements
Java supports two selection statements: if and switch.
These statements allow you to control the flow of your
program’s execution based upon conditions known only during
run time.
If
if (condition) statement1;
else statement2;
CODING DEMO
if-else
if (condition)
{
// condition is true, Executes this block if
}
else CODING DEMO
{
// condition is false,Executes this block if
}
nested-if
if (condition1)
// Executes when condition1 is true
if (condition2) CODING DEMO
{
// Executes when condition2 is true
}
The if-else-if Ladder
if(condition)
statement;
else if(condition)
statement;
else if(condition)
statement;
CODING DEMO
.
.
.
else
statement;
switch
switch (expression) {
case value1:
// statement sequence
break;
case value2:
// statement sequence
break;
CODING DEMO
.
.
.
case valueN:
/ statement sequence
break;
default:
// default statement sequence
}
Loop Statements
In Java, we have three types of loops that execute similarly.
However, there are differences in their syntax and condition
checking time.
for loop
while loop
do-while loop
Java for loop
for (initialization; condition; increment/decrement)
//block of statements
CODING DEMO
while loop
while(condition){
//looping statements
CODING DEMO
}
do-while loop
do
//statements
} CODING DEMO
while (condition);
Jump Statements
[Link] statement
[Link] statement CODING DEMO
[Link] statement
The break statement is used to break the current flow of the program and
transfer the control to the next statement.
[Link] statement
The continue statement doesn't break the loop, whereas, it skips the specific
part of the loop and jumps to the next iteration of the loop immediately.