Skip to main content

Flow of control in JAVA

Flow of control in JAVA

Control statements are used in programming languages to cause the flow of control to advance and branch based on changes to the state of a program.  In Java, control statements can be divided under the following three¢ categories: 

Ø  Decision making statement  or Selection statements
Ø  Iteration statements
Ø  Jump statements
Ø  Decision Making Statement in Java

Decision making statements

Decision making statements is also called selection statement. That is depending on the condition block need to be executed or not which is decided by condition. If the condition is "true" statement block will be executed, if condition is "false" then statement block will not be executed. In java there are three types of decision making statement.

Ø  If-then statement
Ø  if-else statement
Ø  if...else if...else Statement
Ø  nested if statement
Ø  switch statement

Ø if-then Statement
if-then is most basic statement of Decision making statement. It tells to program to execute a certain part of code only if particular condition is true.

Syntax
if(condition)
 {
   Statement(s)
 }
Example if statement
class Hello
{
int a=10;
public static void main(String[] args)
{
if(a<15)
{
System.out.println("Hello good morning!");
}
}
}
Output
Hello good morning

Ø if-else statement
In general it can be used to execute one block of statement among two blocks, in java language if and else are the keyword in java.

Syntax
 if(condition)
 {
  Statement(s)
 }
 else
 {
  Statement(s)
 }

In the above syntax whenever condition is true all the if block statement are executed, remaining statement of the program by neglecting. If the condition is false else block statement executed and neglecting if block statements.

Examples:
public class IfElseExample {  
public static void main(String[] args) {  
    int number=13;  
    if(number%2==0){  
        System.out.println("even number");  
    } else{  
        System.out.println("odd number");  
    }  
}  
}  
Output:
odd number


Ø The if...else if...else Statement

if statement can be followed by an optional else if...else statement, which is very useful to test various conditions using single if...else if statement. When using if, else if, else statements there are a few points to keep in mind. if can have zero or one else's and it must come after any else if’s. if can have zero to many else if's and they must come before the else. Once an else if succeeds, none of the remaining else if's or else's will be tested.

Syntax
Following is the syntax of an if...else statement −
if(Boolean_expression 1) {
   // Executes when the Boolean expression 1 is true
}else if(Boolean_expression 2) {
   // Executes when the Boolean expression 2 is true
}else if(Boolean_expression 3) {
   // Executes when the Boolean expression 3 is true
}else {
   // Executes when the none of the above condition is true.
}
Example
public class Test {
   public static void main(String args[]) {
      int x = 30;
      if( x == 10 ) {
         System.out.print("Value of X is 10");
      }else if( x == 20 ) {
         System.out.print("Value of X is 20");
      }else if( x == 30 ) {
         System.out.print("Value of X is 30");
      }else {
         System.out.print("This is else statement");
      }
   }
}
This will produce the following result −
Output
Value of X is 30


Ø Nested IF Statements

You can nest IF Statements. (This also applies to IF ... ELSE and IF ... ELSE IF statements.) Nesting an IF Statement just means putting one IF Statement inside of another. For example, suppose you want to find out if somebody is younger than 18, but older than 16. You want to display a different message for the over 16s. You start with the first IF Statement:

if ( user < 19 ) {
System.out.println( "18 or younger");
}

To check for over 16, you can place a second IF Statement inside of the one you already have. The format is the same:

if ( user < 19 ) {
if ( user > 16 && user < 19 ) {
System.out.println( "You are 17 or 18");
}
}

So the first IF Statement catches the user variable if it's less than 19. The second IF Statement narrows the user variable down even further, for ages over 16 and under 19.



Java Switch Statement

.A switch statement allows a variable to be tested for equality against a list of values. Each value is called a case, and the variable being switched on is checked for each case. The Java switch statement executes one statement from multiple conditions

Syntax
The syntax of enhanced for loop is −
switch(expression) {
   case value :
      // Statements
      break; // optional
      case value :
      // Statements
      break; // optional
      // You can have any number of case statements.
   default : // Optional
      // Statements
}

The following rules apply to a switch statement −
Ø  The variable used in a switch statement can only be integers, convertable integers (byte, short, char), strings and enums.
Ø  You can have any number of case statements within a switch. Each case is followed by the value to be compared to and a colon.
Ø  The value for a case must be the same data type as the variable in the switch and it must be a constant or a literal.
Ø  When the variable being switched on is equal to a case, the statements following that case will execute until a break statement is reached.
Ø  When a break statement is reached, the switch terminates, and the flow of control jumps to the next line following the switch statement.
Ø  Not every case needs to contain a break. If no break appears, the flow of control will fall through to subsequent cases until a break is reached.
Ø  A switch statement can have an optional default case, which must appear at the end of the switch. The default case can be used for performing a task when none of the cases is true. No break is needed in the default case.


Flow Diagram


Example:
 public class SwitchExample {  
public static void main(String[] args) {  
    int number=20;  
    switch(number){  
    case 10: System.out.println("10");break;  
    case 20: System.out.println("20");break;  
    case 30: System.out.println("30");break;  
    default:System.out.println("Not in 10, 20 or 30");  
    }  
}  
}  
Output:
20

Java Switch Statement is fall-through

The java switch statement is fall-through. It means it executes all statement after first match if break statement is not used with switch cases.

Example:
public class SwitchExample2 {  
public static void main(String[] args) {  
    int number=20;  
    switch(number){  
    case 10: System.out.println("10");  
    case 20: System.out.println("20");  
    case 30: System.out.println("30");  
    default:System.out.println("Not in 10, 20 or 30");  
    }  
}  
}  
Output:
20
30
Not in 10, 20 or 30


Iteration  Statement in Java

Iteration statements cause statements (or compound statements) to be executed zero or more times, subject to some loop-termination criteria. When these statements are compound statements, they are executed in order, except when either the break statement or the continue statement is encountered.
Loops are basically means to do a task multiple times, without actually coding all statements over and over again. For example, loops can be used for displaying a string many times, for counting numbers and of course for displaying menus.
Loops in Java are mainly of three types :-

1. 'while' loop
2. 'do while' loop
3. 'for' loop

while statement

The while loop is Java’s most fundamental loop statement. It repeats a statement or block while its controlling expression is true. Here is its general form:

while(condition) {
    // body of loop
}

The condition can be any boolean expression. The body of the loop will be executed as long as the conditional expression is true.

Here is more practical example.
// Demonstrate the while loop.
class While {
    public static void main(String args[]) {
        int n = 10;
        while (n > 0) {
            System.out.println("tick " + n);
            n--;
        }
    }
}
The ouput of the program is:
tick 10
tick 9
tick 8
tick 7
tick 6
tick 5
tick 4
tick 3
tick 2
tick 1


2. do-while statement

The do-while loop always executes its body at least once, because its conditional expression is at the bottom of the loop. Its general form is:

do{
    // body of loop
} while(condition);

Each iteration of the do-while loop first executes the body of the loop and then evaluates the conditional expression. If this expression is true, the loop will repeat. Otherwise, the loop terminates. As with all of Java’s loops, condition must be a Boolean expression.
The program presented in previous while statement can be re-written using do-while as:

// Demonstrate the do-while loop.
class DoWhile {
    public static void main(String args[]) {
        int n = 10;
        do {
            System.out.println("tick " + n);
            n--;
        } while (n > 0);
    }
}


3. for loop

Here is the general form of the traditional for statement:

for(initialization; condition; iteration) 
{
  // body of for loop
}

The program from previous example can be re-written using for loop as:

// Demonstrate the for loop.
class ForTick {
    public static void main(String args[]) {
        int n;
        for (n = 10; n > 0; n--) System.out.println("tick " + n);
    }      
}

The ouput of the program is same as output from program in while loop.
There can be more than one statement in initilaization and iteration section. They must be separated with comma.

Here, we've presented the example to illustrate this.
// more than one statement using the comma.
class Comma {
    public static void main(String args[]) {
        int a, b;
        for (a = 1, b = 4; a < b; a++, b--) {
            System.out.println("a = " + a);
            System.out.println("b = " + b);
        }
    }
}

The ouput of the program is:
a = 1
b = 4
a = 2
b = 3

Here, the initialization portion sets the values of both a and b. The two comma separated statements in the iteration portion are executed each time the loop repeats.


Nested Loops

Loops can be nested as per requirement. Here is example of nesting the loops.
// nested loops
class NestedLoop {
    public static void main(String args[]) {
        int i, j;
        for (i = 0; i < 8; i++) {
            for (j = i; j < 8; j++)
                 System.out.print(".");
            System.out.println();
        }
    }
}

Here, two for loops are nested. The number times inner loop iterates depends on the value of i in outer loop.

The output of the program is:
........
.......
......
.....
....
...
..
.

The Infinite Loop:

A loop becomes infinite loop if a condition never becomes false. The for loop is traditionally used for this purpose. Since none of the three expressions that form the for loop are required, you can make an endless loop by leaving the conditional expression empty.
int i=1;
   for( ; ; )
   {
        System.out.println(i);
   }
}

When the conditional expression is absent, it is assumed to be true. You may have an initialization and increment expression, but Java programmers more commonly use the for(;;) construct to signify an infinite loop.


Jump statement in JAVA
1.  
  break statement : When a break statement is encountered inside a loop, the loop is terminated and program control resumes at the next statement following the loop. Here is a simple example:

// This program demonstrates   break to exit a loop.
public class BreakDemo
{
   public static void main(String[] args)
   {
      for (int i = 1; i <= 10; i++)
      {
         if (i == 5)
         {
            break;    // terminate loop if i is 5
         }
         System.out.print(i + " ");
      }
      System.out.println("Loop is over.");
   }
}

Output :
2 3 4 Loop is over.

2. continue statement : When a continue statement is encountered inside the body of a loop, remaining statements are skipped and loop proceeds with the next iteration. Here is a simple example.

// This program demonstrates continue  to skip remaining statements of iteration.
public class ContinueDemo
{
   public static void main(String[] args)
   {
      for (int i = 1; i <= 10; i++)
      {
         if (i % 2 == 0)
         {
            continue;    // skip next statement if i is even
         }
         System.out.println(i + " ");
      }
   }
}
Output :
1 3 5 7 9


JAVA Jump statement can be used in two ways:

Labeled and without labeled for example :
Default usage: e.g.
while (Some condition) {
  if ( a specific condition )
  break;        //Default usage
  else
  normal business goes here..
}

Another way is to use with a label.
hackit:
while (Some condition) {
  if ( a specific condition )
  break hackit;       //Usage with label
  else
  normal business goes here..
}

 A label is any valid Java identifier followed by a colon. e.g. outer:, inner:, inner123:, inner_: etc. Whenever during a program execution, a labeled break statement is encountered that control immediately goes out of enclosing labeled block. Similarly, labeled continue will bring control back to start. Just like in normal break and continue statements, with additional names given to blocks.

Let’s look at more example usages:
outer: for (int i = 0; i &lt; 10; i++) {
  inner: for (int j = 10; j > 0; j--) {
    if (i != j) {
      System.out.println(i);
      break outer;
    }else{
      System.out.println("-->>" + i);
      continue inner;
    }
  }
}

//OR

int a = 10;
int b = 12;
 block1: {
    if (a &lt; 0) {
      break block1;
    }
    if (b &lt; 0) {
      break block1;
    }
    System.out.println( a + b );
  }
}

Bullet points
Ø  Java does not have a general goto statement.
Ø  The statements break and continue in Java alter the normal control flow of compound statements. They can use labels which are valid java identifiers with a colon.
Ø  Labeled blocks can only be used with break and continue statements.
Ø  They must be called within its scope. You can not refer them scope of labeled block.
Ø  The break statement immediately jumps to the end (and out) of the appropriate compound statement.
Ø  The continue statement immediately jumps to the next iteration (if any) of the appropriate loop.
Ø  A continue statement does not apply to a switch statement or a block statement, only to compound statements that loop: for, while, and do.

Comments