10-Conditional statements in java

  • An if statement can be followed by an optional else statement. Else statement executes when the Boolean expression is false.
  • Now lets see an example with use of Scanner class in util package.

import java.util.Scanner;

public class Testing {
     public static void main(String args[]){

          Scanner s = new Scanner(System.in);
          System.out.println("Enter marks :");
          double marks = s.nextDouble();

          if(marks > 50){ // the expression should return a boolean value
               System.out.println("Pass");
          }else{
               System.out.println("Fail");
          }

     }
}

  • If Else ladder – In here else part should come last.

import java.util.Scanner;

public class Testing {
     public static void main(String args[]){

          Scanner s = new Scanner(System.in);
          System.out.println("Enter marks :");
          double marks = s.nextDouble();

          if(marks >= 75){ // the expression should return a boolean value
               System.out.println("A Pass");
          }else if(marks >=65 ){
               System.out.println("B pass");
          }else if(marks >= 55){
               System.out.println("C pass");
          }else{
               System.out.println("Fail");
          }

     }
}

  • Extreme if else

import java.util.Scanner;

public class Testing {
    public static void main(String args[]){

         Scanner s = new Scanner(System.in);
         System.out.print("Enter marks :");
         double marks = s.nextDouble();

         if(marks == 75){
              System.out.println("mark is 75");
         }

         System.out.println("After if");

         if(marks != 75){
              System.out.println("mark is not 75");
         }
     }
}

  • Nested if in java

import java.util.Scanner;

public class Testing {
    public static void main(String args[]){

        Scanner s = new Scanner(System.in);
        System.out.print("Enter marks :");
        double marks = s.nextDouble();

        if(marks >= 50){
            if(marks >= 75){
                  System.out.println("A pass");
            }else if(marks >= 65){
                  System.out.println("B pass");
            }else{
                  System.out.println("C pass");
            }
        }else{
             System.out.println("fail");
        }

    }
}

NOTE :- If we didn’t use the curly brackets then only the line immediately after if condition belongs to it.

 

Leave a comment