Java Conditional Statement

If-else-if ladder

An if-else-if ladder is a control structure in programming that is based upon a sequence of nested ifs.

Syntax:

if(condition)
statement;
else if(condition);
statement;
else if(condition);
statement;
. . . . . . . . .
. . . . . . . . .
else
statement;

Working:

The if statements are executed from the top down.As soon as one of the conditions controlling the if is true,the statement associated with that if is executed, and the rest of the ladder is bypassed.If none of the conditions is true, then the final else statement will be executed.


The final else statement is optional and serves as a default case if none of the conditions are true;that is, if all other conditional tests fail, then the last else statement is performed.If there is no final else and all other conditions are false,then no action will take place.

#Java program to demonstrate if-else-if ladder

Program-1: A java program to find the largest number among three numbers.

import java.util.Scanner;
  nbsp;  public class IncomeTaxCalculator {
     public static void main(String[] args) {
     Scanner s = new Scanner(System.in);
     System.out.println("Enter total amount of your income:");
     int income = s.nextInt();
     int tax;
     if (income < 500000) {
     tax = 0;
     } else if (income >= 500000 && income < 1000000) {
     tax = (int) (income * 0.2);
     } else if (income >= 1000000 && income < 1500000) {
     tax = (int) (income * 0.3);
     } else {
     tax = (int) (income * 0.4);
     }
     System.out.println("Your tax is: " + tax);
    }
}


/*OUTPUT*/

Enter total amount of your income:
4000000
Your tax is: 1600000

Program-2:A Java program for grading systems.

import java.util.Scanner;
     public class ApnaStudy{
     public static void main(String[] args) {
     Scanner scanner = new Scanner(System.in);

     System.out.println("Enter the marks obtained (0-100):");
     int marks = scanner.nextInt();

     char grade;
     if (marks >= 90) {
     grade = 'A';
     } else if (marks >= 80) {
     grade = 'B';
     } else if (marks >= 70) {
     grade = 'C';
     } else if (marks >= 60) {
     grade = 'D';
     } else if (marks >= 50) {
     grade = 'E';
     } else {      grade = 'F'; // Failing grade
     }
     System.out.println("Your grade is: " + grade);
    }
}


/*OUTPUT*/

Enter the marks obtained (0-100):
50
Your grade is: E

Previous Next