Snippets

Check Leap Year with Kotlin

Posted by I. B. Gd Pramana A. Putra, 12 Mar 22, last updated 17 Jul 22

A Kotlin code example or code snippet to check leap year. This code is showing you how to create a simple Kotlin program that checks whether a year is a leap year.

According to Wikipedia: a leap year is a year that has one additional day in order to adjust the calendar to the astronomical year.

The logic to check for leap year:

  • if (year is not divisible by 4) then (it is a common year)
  • else if (year is not divisible by 100) then (it is a leap year)
  • else if (year is not divisible by 400) then (it is a common year)
  • else (it is a leap year)

The years input that we will give & its expected output are:

  • 2020 is a leap year
  • 2019 is not a leap year
  • 2018 is not a leap year
  • 2000 is a leap year -1900 is not a leap year

Kotlin Code Examples to Check for Leap Year There are some Kotlin code examples that will help you run a simple code program to check whether a year is a leap year.

Example #1

You can immediately run the following code on various IDEs where the IDE environment is already associated with the Kotlin compiler, for example, Visual Studio, Visual Studio Code, Atom, NetBeans and JetBrains IntelliJ.

fun main(args: Array<String>) { fun isLeapYear(year: Int) = year % 400 == 0 || (year % 100 != 0 && year % 4 == 0) print(isLeapYear(2019)) }


This first sample of Kotlin code for checking leap years is very simple and straight to the point.

The output is only printing out whether the inputted year is a leap year with a boolean value. Let’s try give 2019 as the value to check, then it will return the following result:

False


## Example #2
The following Kotlin code uses the Nested If and Comparison Operators.

```kotlin
fun main(args: Array<String>) {

    val year = 2019var leap = false

    if (year % 4 == 0) {
        if (year % 100 == 0) {
            leap = year % 400 == 0
        } else
            leap = true
    } else
        leap = false

    println(if (leap) "$year is a leap year" else "$year is not a leap year")
}

Output

Input year:
2020 is a leap year

Input year: 2019
2019 is not a leap year

Input year: 2018
2019 is not a leap year

Input year: 2000
2000 is a leap year

Input year: 1900
1900 is not a leap year

Hopefully, these Kotlin code examples to check for a leap year is helpful.

I love sharing code snippets as most of the time, a quick code example is what we're looking for instead of long-written articles. If you think my code snippets are helpful and save you a lot of time, please consider buying me a cup of coffee :)

Support me via · paypal · buymeacoffee · ko-fi · trakteer
Contributed Snippets
Answer & Responses
    No comments yet

Wanna write a response?

You have to login before write a comment to this post.