Java Flow Controls – Part 1

There are two types of flow controls in Java programming language.

  1. Selection
  2. Iteration

In this post we will be looking at only the Selection type. We will continue Iteration type in the next post.

Selection

There are five types of selection algorithms.

  1. if
  2. if else if
  3. if else
  4. ladder if
  5. nested if

1. if

The statement(instruction) inside the if condition will be executed only if the condition in the parameter list is true.

Ex :

int age =36;

if (age>18) {

     System.out.println (“Success !”);

}

The output in the above scenario is Success! since 36 is greater than 18 which makes the condition true.

2.if else

If the condition in parameter list gets false, then the program goes to else part without executing the print statement in if().

Ex :

int age = 16;

if (age>18){

     System.out.println (“Success !”);

} else {

     System.out.println (“Try Again !”);

}

Prints out Try Again! since 16 is less than 18 which makes the condition false inside the parameter list.

3.if else if

In if else if, it works as a chain until it meets the point where parameter list gets the value True.

Ex :

int myAge = 20;

int broAge = 15;

if (myAge==broAge){

System.out.println (“Twins !”);

}else if  (myAge<broAge){

System.out.println (“Brother is ayya !”);

} else {

System.out.println (“Brother is malli !”);

}

This outputs Brother is malli! since the broAge is less than myAge which brings the program to else part.

4.Ladder if

This works as a ladder which means that always program runs through till it meets a position where the parameter list is True.

Ex :

int mark=67;

if (mark>100){

System.out.println (“Above 100 !”);

}

else if ( 75<mark){

System.out.println (“A”);

}

else if (65<mark){

System.out.println (“B”);

}

else if (55<mark){

System.out.println (“C”);

}

else if (30<mark){

System.out.println (“S”);

}

else if (mark>0){

System.out.println (“F”);

}

else{

System.out.println (“Less than 0 !”);

}

This prints out B since 67 is greater than 65 which makes the condition true at that position.

5.Nested if

In this algorithm, the program can execute the statements in the inner statements only if the first condition is True.

Ex :

if(color is good?){

if(name is correct){

System.out.pprintln(“Maching!”);

}

else{

System.out.pprintln(“Not Maching!”);

}

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s