Java - Control Flow Statements

Programming statements are usually executed from top to bottom. Control statements allow you to break that flow allowing you to execute code based on decisions or repeating code until a condition is met. In this code snippet we take a look at a few control statements.

If/else Statements

An "if/else and else if" is a simple control flow statement that allows you to execute a particular block of code based on a condition. The condition needs to evaluate to either true or false. Take a look at the example below.

  1. class Program {   
  2.   
  3.     public static void main(String args[]){   
  4.            
  5.         int age = 13;   
  6.            
  7.         if (age > 11){   
  8.             System.out.println( "You must be in secondary school");   
  9.         }else{   
  10.             System.out.println( "You must be in primary school");   
  11.         }   
  12.     }   
  13. }  

The sample code above demonstrates a simple control flow statement. Notice how the statement can execute different blocks of code based upon the value of variable age. This type of statement is useful for "one or the other" type of situations - if the condition evaluates to true then do something, "else" do another thing. However there are situations where you might want to check several conditions. The code sample below shows how to use "else if" to check for several conditions before finally resulting to "else" if none of the conditions evaluated to true.

  1. class Program {   
  2.   
  3.     public static void main(String args[]){   
  4.            
  5.         String fruit =  "Orange";   
  6.            
  7.         if (fruit ==  "Apple"){   
  8.             System.out.println( "So you like apples?");   
  9.         } else if (fruit ==  "Orange"){   
  10.             System.out.println( "Oranges are nice");   
  11.         } else if (fruit ==  "Grape"){   
  12.             System.out.println( "Not so fond of grapes");   
  13.         } else {   
  14.             System.out.println( "I like " + fruit);   
  15.         }   
  16.     }   
  17. }  

No comments:

Post a Comment