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 ;
     }

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