Wednesday, 5 February 2014

Control flow statements : Decision Making: if-then, if-else, if-else if-else

Java provides control flow statements
     for decision making (if, if-else, switch) and
     for looping (for, while, do-while)

Block of statements
In java the statements between { } are called block of statements.
     {
          //block of code
     }

Decision making statements
if statement
if ” tell the program execute the section of code when the condition evaluates to true.
     Syntax
          if(condition){
               // Executes if the condition true
          }

Example
class Grades{
 public static void main(String args[]){ 
  int marks = 20;
  if(marks < 35 ){
   System.out.println("You failed in the Exam. Better luck next time");
  }
 }
}
Output
You failed in the Exam. Better luck next time

Some points to remember
1. In java the condition in the if must evaluates to boolean value, other wise compiler will throw error

Example
class Grades{
 public static void main(String args[]){
  int var1;
  if(var1 = 10){
  
  }
 }
}

When you try to compile the above program, you will get the below error
Grades.java:5: error: incompatible types
 if(var1 = 10){
 ^
 required: boolean
 found: int
1 error
    if-else statement
        Syntax:
        if(condition){

        }
        else{

        }

    If the condition true, then if block code executed. other wise else block code executed.

    Example
    class Grades{
     public static void main(String args[]){ 
      int marks = 36;
      
      if(marks < 35)
       System.out.println("You are failed");
      else
       System.out.println("You are passed");
     }
    }
    

    Output
    You are passed
    

    Observation
    In the above program we haven't written the if, else block codes in between { }, since if there is only one statement in between the blocks, we can omit { }.

    if-else if-else
    By using if-else if-else construct, you can choose number of alternatives.

    An 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.

    class Grades{
     public static void main(String args[]){
      int marks = 69;
      
      if(marks < 35)
       System.out.println("You are failed");
      else if( marks < 50)
       System.out.println("You are passed and got third class");
      else if( marks < 60)
       System.out.println("You are passed and got second class");
      else if( marks < 70)
       System.out.println("You are passed and got first class");
      else
       System.out.println("You are passed and got distinction");
     }
    }
    

    Output
    You are passed and got first class
    


    other Operators                                                 Control flow statements                                                 Home

    No comments:

    Post a Comment