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.
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.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
Topic: Introduction | Language: Java