Java Conditional Statement

Nested-if statement

In java, nested if statements allows you to multi-level decision-making logic within your code. When an entire if-else statement can be written within either the body of the if statement or the body of an else statement.This is called ‘nesting’ of ifs.


Note:when you nest ifs, the main thing to remember is that an else statement always refers to the nearest if statement that is within the same block as the else and that is not already associated with an else.

Syntax:


if (condition1) {
// Code block to execute if condition1 is true

if (condition2) {
// Code block to execute if both condition1 and condition2 are true
} else {
// Code block to execute if condition1 is true but condition2 is false
}
} else {
// Code block to execute if condition1 is false
}

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

import java.util.Scanner;
  nbsp;  public class ApnaStudy {
     public static void main(String[] args) {
     Scanner sc = new Scanner(System.in);
     System.out.println("Enter value of a");
     int a = sc.nextInt();
     System.out.println("Enter value of b");
     int b = sc.nextInt();
     System.out.println("Enter value of c");
     int c = sc.nextInt();
     // Nested if-else statements to find the greatest number
     if (a >= b) {
     if (a >= c) {
     System.out.println("a is greater: " + a);
     } else {
     System.out.println("c is greater: " + c);
     }
     } else {
     if (b >= c) {
     System.out.println("b is greater: " + b);
     } else {
     System.out.println("c is greater: " + c);
     }
    }
   }
}


/*OUTPUT*/

Enter value of a 30
Enter value of b 40
Enter value of c 33
b is greater: 40

Program-2: A java program to check if a given number is positive, negative or zero.

import java.util.Scanner;
public class ApnaStudy{
     public static void main(String[] args) {
     int number = -5;

     if (number > 0) {
     System.out.println("The number is positive.");
     } else {
     if (number < 0) {
     System.out.println("The number is negative.");
     } else {
     System.out.println("The number is zero.");
     }
    }
   }
}


/*OUTPUT*/

The number is negative.

Previous Next