IF ELSE Statement in Java


The Java if-else statement also tests the condition.The condition is any expression that returns a boolean value. An if statement executes code conditionally depending on the result of the condition in parentheses. When condition in parentheses is true it will enter to the block of if statement which is defined by curly braces like open braces and close braces.

Opening bracket till the closing bracket is the scope of the if statement. The else block is optional and can be omitted.It runs if the if statement is false and does not run if the if statement is true because in that case if statement executes.

  Syntax:
     if( condition )
     {
        // body of the statement if condition is true ;
     }
     else
     {
        // body of the statement if condition is false ;
     }

This is a Java program that checks whether a given year is a leap year or not using an if-else statement. Here's how the program works:

  • First, it declares an integer variable called year.
  • Then, it prints the message "Enter Year : " using the System.out.println() method.
  • It creates a Scanner object called in to read the input from the user.
  • It reads the user's input using the in.nextInt() method and stores it in the year variable.
  • The program then checks if the year variable is a leap year or not by using the following condition inside the if statement:
    • If the year is divisible by 4 and not divisible by 100, it is a leap year.
    • If the year is divisible by both 100 and 400, it is a leap year.
    • Otherwise, it is not a leap year.
  • If the condition is true, the program prints the message "Year <year> is a leap year" using the System.out.println() method.
  • If the condition is false, the program prints the message "Year <year> is not a leap year" using the System.out.println() method.

Source Code

import java.util.Scanner;
 
public class if_else_statement {
    public static void main(String args[]) {
        int year;
        System.out.println("Enter Year : ");
        Scanner in = new Scanner(System.in);
        year = in.nextInt();
        if (year % 4 == 0 || (year % 100 == 0 && year % 400 == 0)) {
            System.out.println("Year " + year + " is a leap year");
        } else {
            System.out.println("Year " + year + " is not a leap year");
        }
 
    }
}
 
 
 

Output

Enter Year :
1900
Year 1900 is a leap year
Enter Year :
2022
Year 2022 is not a leap year
To download raw file Click Here

Basic Programs