Control Structures in Java
- allow us to change the ordering of how the statements in our programs are executed
● Decision Control Structures - which allow selection of specific sections of code to be executed
- if
- if-else
- if - else if
- switch
● Repetition Control Structures – which allow executing specific sections of code a number of
times
- while
- do-while
- for
● Branching Statements – which allow redirection of program flow
- break
- continue
- return
Syntax and Examples
if-statement has the form:
if ( boolean_expression ) statement; or
if ( boolean_expression )
{statement 1;statement 2;}
-where: boolean _expression is either a boolean expression or boolean variable
Ex:
int grade = 68;if ( grade > 60 )
System.out.println ("Congratulations! ") ;
if-else statement has the form:
if ( boolean_expression )
{statement 1;statement 2;. . .}
else
{statement 3;statement 4;. . .}
Ex:
int grade = 68; if ( grade > 60 )
System.out.println ("Congratulations! ");
Else System.out.println ("Sorry you failed") ;
if-else-if statement has the form:
if ( boolean_expression1 )statement 1;
else if ( boolean_expression2 )statement 2;
else statement 3;
Ex:
int grade = 68;if ( grade > 90 )
{System. out. println ("Very good! ") ;}
else if ( grade > 60 )
{System. out. println ("Very good! ") ;}
else
{System. out. println ("Sorry you failed") ;}
switch statement has the form:
switch( switch_expression )
{case case_selector1:
statement1;//
statement2;//block 1
break;
case case_selector2:
statement1;//
statement2;//block2
break;
:
default:
statement1;//statement2;//block n}
-where: switch _expression - is an integer or character expression
case_selector1, case_selector2 and so on - are unique integer or character constants.
Ex:
public class Grade { publicstatic void main( String[] args )
{ int grade = 92;5
switch(grade)
{ case 100: System.out.println( "Excellent!" ); break;
case 90: System.out.println("Good job!" );break;
case 80: System.out.println("Study harder!");
break;
default: System.out.println("Sorry, you failed."); } }}
while loop has the form:
while ( boolean_expression )
{statement 1;statement 2;. . .}
Ex:
Int x = 0;while (x<10)
{System. out. println (x) ;x++;}
do-while loop has the form:
do {statement 1;statement 2;. . .}
while ( boolean_expression ) ;
Ex:
int x = 0;
do {System. out. println (x) ;x++;}
while (x<10) ;
for loop has the form:
for(InitializationExpression;LoopCondition;StepExpression)
{statement1;statement2;. . .}
-where: InitializationExpression -initializes the loop variable
LoopCondition - compares the loop variable to some limit value
StepExpression - updates the loop variable.
Ex:
int i;
for ( i = 0; i < 10; i++ )
{System. out. println (i) ;}