English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Kotlin check if it is a leap year

Kotlin Comprehensive Examples

In this program, you will learn how to check if a given year is a leap year in Kotlin. It uses if else statements and when statements to check.

is a leap year4is divisible by400 is divisible by, only century years are leap years, but not those ending with 00. Only when it can be

Example1:Using if else statements to check the Kotlin program for Ko year

fun main(args: Array<String>) {
    val year = 1900
    var leap = false
    if (year % 4 == 0) {
        if (year % 100 == 0) {
            //year can be divisible by400 is divisible by, therefore it is a leap year
            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.")
}

When running the program, the output is:

1900 is not a leap year.

In the above program, the given year1900 is stored in the variable year.

  • Because1900 is divisible by4is divisible by, and it is a century year (ending with 00), while leap years can be400 is divisible by. Because1900 is not divisible by400 is divisible by, so1900 is not a leap year.

  • However, if we change year to2000, then it can be4is divisible by, and it is a century year, and it can also be400 is divisible by. Therefore,2000 is a leap year.

  • Similarly, if we change the year to2012then the year can be4is divisible by, and it is not a century year, so2012is a leap year. We do not need to check2012The year can be divisible by400 is divisible by.

The equivalent Java code is as follows:Java program to check for leap year

Example2:Kotlin program uses when expression to check for leap year

fun main(args: Array<String>) {
    val year = 2012
    var leap = false
    leap = when {
        year % 4 == 0 -> {
            when {
                year % 100 == 0 -> year % 400 == 0
                else -> true
            }
        }
        else -> false
    }
    println(if (leap) "$year is a leap year." else "$year is not a leap year.")
}

When running the program, the output is:

2012 It is a leap year.

In the above program, we used the when expression instead of if else statements.

The way the when expression works is as follows:

  • If the year (year) can be 4 When divisible:

    • If it can be4If divisible, check again whether year can be400 evenly divisible, then return true or false

    • when another expression is entered, check if year can be100 evenly

    • If it cannot be divided by100, then year is not a century year (ending with 00), then return true

  • If year cannot be4If it is divisible, return false

According to the value of leap, it uses inline if else to print the output.

Kotlin Comprehensive Examples