Nested if in Java programming


It is perfectly all right if we write an entire if-else construct within either the body of the if statement or the body of an else statement.

Syntax :

if( boolean_expression 1) {
   /* Executes when the boolean expression 1 is true */
   if(boolean_expression 2) {
      /* Executes when the boolean expression 2 is true */
   }
}               
                                    

Example:

Java Program to check the given natural number is even or odd.
Test.java Copy Code
import java.util.Scanner;

public class Test {
    public static void main(String[] args) {
        Scanner sc; // Declare a Scanner object
        sc = new Scanner(System.in); // Initialize the Scanner object to read input from the console
        int x; // Declare an integer variable 'x'

        System.out.print("Enter any number: "); // Prompt the user to enter a number
        x = sc.nextInt(); // Read an integer input from the user and store it in 'x'

        // Check if the entered number is greater than 0
        if (x > 0) {
            // If true, check if the number is even or odd
            if (x % 2 == 0) {
                System.out.print("X is EVEN"); // If even, print "X is EVEN"
            } else {
                System.out.print("X is ODD"); // If odd, print "X is ODD"
            }
        } else {
            // If false (i.e., the number is not greater than 0), print "Not a Natural Number"
            System.out.print("Not a Natural Number");
        }
    } // main method closed
} // class closed

OUTPUT 1:
Enter any number: 12
X is EVEN
                                
OUTPUT 2:
Enter any number: 3
X is ODD
                                
OUTPUT 3:
Enter any number: -12
Not a Natural Number
                                



🚀 Quick Knowledge Check

Topic: Introduction | Language: Java

Q1. Before being officially called Java, which of the following was NOT an early name of the language?
Q2. Which edition of Java is specifically designed for large-scale web and enterprise applications?
Q3. Who developed Java, and in which year did its development begin?
Q4. Which feature of Java is described by the phrase 'Write Once, Run Anywhere' (WORA)?
Q5. Which of the following is NOT a feature of Java ?