topics content@scaler.com
    • Create new note
    • Create a note from template
      • Sharing URL Link copied
      • /edit
      • View mode
        • Edit mode
        • View mode
        • Book mode
        • Slide mode
        Edit mode View mode Book mode Slide mode
      • Customize slides
      • Note Permission
      • Read
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Write
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Engagement control Commenting, Suggest edit, Emoji Reply
    • Invite by email
      Invitee

      This note has no invitees

    • Publish Note

      Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

      Your note will be visible on your profile and discoverable by anyone.
      Your note is now live.
      This note is visible on your profile and discoverable online.
      Everyone on the web can find and read all notes of this public team.
      See published notes
      Unpublish note
      Please check the box to agree to the Community Guidelines.
      View profile
    • Commenting
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
      • Everyone
    • Suggest edit
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
    • Emoji Reply
    • Enable
    • Versions and GitHub Sync
    • Note settings
    • Note Insights New
    • Engagement control
    • Transfer ownership
    • Delete this note
    • Save as template
    • Insert from template
    • Import from
      • Dropbox
      • Google Drive
      • Gist
      • Clipboard
    • Export to
      • Dropbox
      • Google Drive
      • Gist
    • Download
      • Markdown
      • HTML
      • Raw HTML
Menu Note settings Note Insights Versions and GitHub Sync Sharing URL Create Help
Create Create new note Create a note from template
Menu
Options
Engagement control Transfer ownership Delete this note
Import from
Dropbox Google Drive Gist Clipboard
Export to
Dropbox Google Drive Gist
Download
Markdown HTML Raw HTML
Back
Sharing URL Link copied
/edit
View mode
  • Edit mode
  • View mode
  • Book mode
  • Slide mode
Edit mode View mode Book mode Slide mode
Customize slides
Note Permission
Read
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Write
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Engagement control Commenting, Suggest edit, Emoji Reply
  • Invite by email
    Invitee

    This note has no invitees

  • Publish Note

    Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

    Your note will be visible on your profile and discoverable by anyone.
    Your note is now live.
    This note is visible on your profile and discoverable online.
    Everyone on the web can find and read all notes of this public team.
    See published notes
    Unpublish note
    Please check the box to agree to the Community Guidelines.
    View profile
    Engagement control
    Commenting
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    • Everyone
    Suggest edit
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    Emoji Reply
    Enable
    Import from Dropbox Google Drive Gist Clipboard
       Owned this note    Owned this note      
    Published Linked with GitHub
    • Any changes
      Be notified of any changes
    • Mention me
      Be notified of mention me
    • Unsubscribe
    --- Title: Java Program to Check Leap Year - Scaler Topics description: In this article, Scaler Topics will teach you how to identify a leap year and showcase a Java program to check whether the given year is a leap year. author: Abhishek Shree Category: Java --- :::section{.abstract} <!-- ## Introduction --> Leap years are those years with 366 days instead of 365. A leap year must satisfy any one of the following two constraints: * It should be divisible by 400 * It should be divisible by four and not by 100 ![Java leap year program](https://scaler.com/topics/images/Java-Leap-Year-Program-577x1024.jpeg) ::: ::: section{methods} ## Methods for Leap Year Program in Java Java provides specific methods to evaluate leap year, which are mentioned below: 1. Using the Ternary Operator for Finding Leap Year 2. Using command-line arguments to check for Leap Year in Java 3. Using Scanner class to check for Leap Year in Java 4. Using if-else statements for Finding Leap Year in Java 5. Using in-built isLeap() method to check for Leap Year in Java ::: :::section{.main} * ## Using the Ternary Operator for Finding Leap Year Program in Java The basic idea of a `ternary operator` in Java is to reduce the `if-else statements`, as those can get cumbersome, as we saw in the earlier method. A general structure for the ternary operator is shown in the image below. ![Leap Year Program in Java](https://scaler.com/topics/images/Leap-Year-Program-in-Java-1024x444.jpeg) A program to find whether a year is a leap or not using ternary operators in Java will need `three nested ternary` operators, one for each of the conditions mentioned in our flowchart. **Code:** ```Java public class LeapYear { public static void main(String[] args) { // The desired year to check. int year = 1998; String result; result = ( (year % 4 == 0 && year % 100 != 0) ? "is a leap year." : (year % 400 == 0) ? "is a leap year." : "is not a leap year." ); // Append the year and format the string System.out.println(year + " " + result); } } ``` **Output:** ```Java 1998 is not a leap year. ``` ### Complexity Time Complexity- O(1) Space Complexity- O(1) ::: :::section{.main} * ## Using command-line arguments to check for Leap Year in Java `Command-line` arguments are stored as strings in the String array passed to the main method in Java classes. We can use this feature to take input directly while running our program after compilation. 1. Here, we take the user input directly from the command line when the Java compiled code is executed. 2. We read arguments from `String[] args` in the `main` method using array syntax and convert them into integers by using the `Integer` class method `Integer.parseInt()` which converts other data types to integers. 3. We place the input in the `checkLeapYear(int year)` method and display whether the given year is a `leap year or not`. **Code:** ```Java public class LeapYear { // Method to check leap year public static void checkLeapYear(int year) { if (year % 400 == 0) { System.out.println(year + " is a leap year."); } else if (year % 100 == 0) { System.out.println(year + " is not a leap year."); } else if (year % 4 == 0) { System.out.println(year + " is a leap year."); } else { System.out.println(year + " is not a leap year."); } } public static void main(String[] args) { if (args.length > 0) { // convert string into integer int year = Integer.parseInt(args[0]); checkLeapYear(year); } else { System.out.println("No arguments provided."); } } } ``` How to run: Store the code in a file named `LeapYear.java`, compile it using: ```Java javac LeapYear.java ``` Execute the class file generated using the following command: ```Java java LeapYear 1998 ``` **Output:** ```Java 1998 is not a leap year. ``` ### Complexity Time Complexity- O(1) Space Complexity- O(1) `Command-line` arguments open a completely new domain for taking inputs in java programs and can be helpful at times. * ### Using Scanner class to check for Leap Year in Java We can access the `Scanner` class to take inputs from the command line in Java. The process is as follows: 1. We import the `Scanner` class from the **Java.util** package. 2. In the `main` method, we create a `Scanner` object (named `s`). 3. Then we scan an integer using `s.nextInt()` method and store it in an integer variable. 4. We supply the value to the `checkLeapYear(int year)` method and display whether the given year is a leap year or not. **Code:** ```Java import java.util.Scanner; // Import the Scanner class public class LeapYear { // Method to check leap year public static void checkLeapYear(int year) { if (year % 400 == 0) { System.out.println(year + " is a leap year."); } else if (year % 100 == 0) { System.out.println(year + " is not a leap year."); } else if (year % 4 == 0) { System.out.println(year + " is a leap year."); } else { System.out.println(year + " is not a leap year."); } } public static void main(String[] args) { Scanner s = new Scanner(System.in); // Create a Scanner object System.out.println("Enter a year to check:"); int year = s.nextInt(); // Read user input from command line checkLeapYear(year); } } ``` **Output:** ```Java Enter a year to check: 1998 1998 is not a leap year. ``` ### Complexity Time Complexity- O(1) Space Complexity- O(1) ::: :::section{.main} * ## Using if-else statements for Finding Leap Program Year in Java The procedure is as follows: 1. Let the year be `y`. 2. We start our `if-else` block and check if the year is `divisible by 400`, if not, if true, the year is a leap year, and we print the same, Otherwise we move to the else if block. 3. If the first else if block, we check if the year is `divisible by 100`. if true, the year is not a leap year, and we print the result; otherwise, we move to the next if block. 4. In the last else if block, we check if the year is `divisible by 4`, and if that turns out to be true the year is a leap year and we display the result, if that condition fails too, we conclude that the year is `not a leap year` in our final else block. ### Code ```Java public class LeapYear { public static void main(String[] args) { // The desired year to check. int year = 1998; // Implementing our algorithm. if (year % 400 == 0) { System.out.println(year + " is a leap year."); } else if (year % 100 == 0) { System.out.println(year + " is not a leap year."); } else if (year % 4 == 0) { System.out.println(year + " is a leap year."); } else { System.out.println(year + " is not a leap year."); } } } ``` ### Output ```Java 1998 is not a leap year. ``` ### Complexity Time Complexity- O(1) Space Complexity- O(1) <!-- ### Explanation * Here, we are checking all the conditions one by one to get the desired result. * Altering the order of statements will `deviate the code` from the `flowchart`, leading to undesired outputs. * We can also use `logical` operators to reduce the number of `if-else` statements in the first snippet. ```Java public class LeapYear { public static void main(String[] args) { int year = 1998; if ((year % 400 == 0) || ((year % 4 == 0) && (year % 100 != 0))) { System.out.println(year + " is a leap year."); } else { System.out.println(year + " is not a leap year."); } } } ``` **Output:** ```Java 1998 is not a leap year. ``` **Note:** We should generally avoid complex combinations of `logical operators` as it reduces the readability of our code and makes it more `prone to bugs`. --> ::: :::section{.main} * ## Using in-built isLeap() method to check for Leap Year in Java Java provides an in-built method isLeap() in the Year class to identify if an input year is leap or not. Let us see its implementation: **Declaration:** ```Java public boolean isLeap() ``` **Code:** ```Java // isLeap() method in Java illustration import java.time.*; import java.util.*; public class CheckLeapYear { public static void main(String[] args) { // Create the Year object: year Year year = Year.of(2020); // Print the result of isLeap method System.out.println(year.isLeap()); } } ``` **Output:** ```Java true ``` ### Complexity Time Complexity- O(1) Space Complexity- O(1) ::: :::section{.summary} ## Conclusion * Leap years are those years that are either divisible by 400 or they are divisible by four and not by 100. * We can find leap years using simple if-else blocks. * We can use ternary operators to present the if-else logic in an elegant manner. * To make the code modular, the whole if-else logic can be shifted to a method that decides and prints whether the input year is leap or not. * Apart from implementing it from scratch, Java also has a `Year` class with inbuilt methods like `isLeap()` to ease some of our work. :::

    Import from clipboard

    Paste your markdown or webpage here...

    Advanced permission required

    Your current role can only read. Ask the system administrator to acquire write and comment permission.

    This team is disabled

    Sorry, this team is disabled. You can't edit this note.

    This note is locked

    Sorry, only owner can edit this note.

    Reach the limit

    Sorry, you've reached the max length this note can be.
    Please reduce the content or divide it to more notes, thank you!

    Import from Gist

    Import from Snippet

    or

    Export to Snippet

    Are you sure?

    Do you really want to delete this note?
    All users will lose their connection.

    Create a note from template

    Create a note from template

    Oops...
    This template has been removed or transferred.
    Upgrade
    All
    • All
    • Team
    No template.

    Create a template

    Upgrade

    Delete template

    Do you really want to delete this template?
    Turn this template into a regular note and keep its content, versions, and comments.

    This page need refresh

    You have an incompatible client version.
    Refresh to update.
    New version available!
    See releases notes here
    Refresh to enjoy new features.
    Your user state has changed.
    Refresh to load new user state.

    Sign in

    Forgot password

    or

    By clicking below, you agree to our terms of service.

    Sign in via Facebook Sign in via Twitter Sign in via GitHub Sign in via Dropbox Sign in with Wallet
    Wallet ( )
    Connect another wallet

    New to HackMD? Sign up

    Help

    • English
    • 中文
    • Français
    • Deutsch
    • 日本語
    • Español
    • Català
    • Ελληνικά
    • Português
    • italiano
    • Türkçe
    • Русский
    • Nederlands
    • hrvatski jezik
    • język polski
    • Українська
    • हिन्दी
    • svenska
    • Esperanto
    • dansk

    Documents

    Help & Tutorial

    How to use Book mode

    Slide Example

    API Docs

    Edit in VSCode

    Install browser extension

    Contacts

    Feedback

    Discord

    Send us email

    Resources

    Releases

    Pricing

    Blog

    Policy

    Terms

    Privacy

    Cheatsheet

    Syntax Example Reference
    # Header Header 基本排版
    - Unordered List
    • Unordered List
    1. Ordered List
    1. Ordered List
    - [ ] Todo List
    • Todo List
    > Blockquote
    Blockquote
    **Bold font** Bold font
    *Italics font* Italics font
    ~~Strikethrough~~ Strikethrough
    19^th^ 19th
    H~2~O H2O
    ++Inserted text++ Inserted text
    ==Marked text== Marked text
    [link text](https:// "title") Link
    ![image alt](https:// "title") Image
    `Code` Code 在筆記中貼入程式碼
    ```javascript
    var i = 0;
    ```
    var i = 0;
    :smile: :smile: Emoji list
    {%youtube youtube_id %} Externals
    $L^aT_eX$ LaTeX
    :::info
    This is a alert area.
    :::

    This is a alert area.

    Versions and GitHub Sync
    Get Full History Access

    • Edit version name
    • Delete

    revision author avatar     named on  

    More Less

    Note content is identical to the latest version.
    Compare
      Choose a version
      No search result
      Version not found
    Sign in to link this note to GitHub
    Learn more
    This note is not linked with GitHub
     

    Feedback

    Submission failed, please try again

    Thanks for your support.

    On a scale of 0-10, how likely is it that you would recommend HackMD to your friends, family or business associates?

    Please give us some advice and help us improve HackMD.

     

    Thanks for your feedback

    Remove version name

    Do you want to remove this version name and description?

    Transfer ownership

    Transfer to
      Warning: is a public team. If you transfer note to this team, everyone on the web can find and read this note.

        Link with GitHub

        Please authorize HackMD on GitHub
        • Please sign in to GitHub and install the HackMD app on your GitHub repo.
        • HackMD links with GitHub through a GitHub App. You can choose which repo to install our App.
        Learn more  Sign in to GitHub

        Push the note to GitHub Push to GitHub Pull a file from GitHub

          Authorize again
         

        Choose which file to push to

        Select repo
        Refresh Authorize more repos
        Select branch
        Select file
        Select branch
        Choose version(s) to push
        • Save a new version and push
        • Choose from existing versions
        Include title and tags
        Available push count

        Pull from GitHub

         
        File from GitHub
        File from HackMD

        GitHub Link Settings

        File linked

        Linked by
        File path
        Last synced branch
        Available push count

        Danger Zone

        Unlink
        You will no longer receive notification when GitHub file changes after unlink.

        Syncing

        Push failed

        Push successfully