Java leap year program | codeYourslf coding on mobile

Java leap year program | codeYourslf coding on mobile, How to check whether a year is leap or not in java programming language
3 min read

Java leap year program

Java leap year program | codeYourslf coding on mobile

Approach:-1 "Check leap year in java using if else"

package CodeYourslf.BasicProgram;

public class leapYear {

  public static void main(String[] args) {

    java.util.Scanner sc = new java.util.Scanner(System.in);

    System.out.println("Enter the year to check leap or not: ");

    int year = sc.nextInt();

    

    if((year % 4 == 0) && (year % 100 != 0) || (year % 400 ) == 0){

      System.out.println("The year is leap");

    }

    

    else{

      System.out.println("The year is not leap");

    }

  }

}

Java leap year program | codeYourslf coding on mobile

Approach:-2 "java leap year program using method"

import java.util.Scanner;

public class leapYearByMethod {

  public static void main(String args[]) {

    Scanner sc = new Scanner(System.in);

    System.out.println("Enter the year to check leap or not");

    int year = sc.nextInt();

    boolean rel = checkLeap(year);

    if (rel) {

      System.out.println("Year is leap");

    } else {

      System.out.println("Year is not leap");

    }

  }

  // Method declaration

  static boolean checkLeap(int year) {

    if (year % 4 == 0) {

      return true;

    }

    if (year % 400 == 0) {

      return true;

    }

    if (year % 100 == 0) {

      return false;

    }

    return false;

  }

}

In this article we are going to understand how to write a java program to check whether a given year is leap nor not.

What is leap year

👉 We know the year in which the february month contain 29 days, called leap year.

- How we can know a year is leap year or not in java programming.

Logic for the program

- Here we have to check for three logics 

1- Check the year is divisible by 4 , 400 and 100 or not.

- The year should be completely divisible by 4 or 400, here in java we can use OR(||) operation to check the condition.

- And the year should not divisible by 100, here we have to use and(&&) operator to check the condition.

   Please go through the code that given in the top of the article, If you found trouble to understand anything then feel free to contact with me. I am always ready to guide the Beginners. ☺️ 

`

You may like these posts

Post a Comment

Hey Please 👏, feel free to share your opinion 🌍