Kotlin Program to Check for Leap Year

In this post, we will go through Kotlin Program to Check for Leap Year.

A given year is leap year if it satisfies below condition –

  • 1. Year is multiple of 400
  • 2. Year is multiple of 4 but not of 100

1. Kotlin Program to Check for leap year

import java.util.*

fun main() {

    val read = Scanner(System.`in`)

    println("Enter Year:")
    val year = read.nextInt()

    val msg = if(checkLeapYear(year)) {
        "Given year is a leap year."
    } else {
        "Given year is not a leap year."
    }

    println(msg)
}

/**
 * Function that check whether given year is leap year or not.
 */
private fun checkLeapYear(year: Int): Boolean {
    return ((year % 400) == 0)
            || (((year % 4) == 0) && ((year % 100) != 0))
}

When you run the program, output will be

Enter Year:
2020
Given year is a leap year.

Here, we have created an object of Scanner. Scanner takes an argument which says where to take input from.
System.`in` means take input from standard input – Keyboard.

read.nextIn() means read anything entered by user before space or line break from standard input – Keyboard.
Input read by scanner is then stored in variable year

checkLeapYear checks whether given year is leap year or not. If yes, it returns true. Otherwise, it returns false.

Finally, we print result value using println() method.

2. Check leap year Using when Block

In the previous example, we used if-else block. Now, we will use when block in kotlin to check for leap leap.

import java.util.*

fun main() {

    val read = Scanner(System.`in`)

    println("Enter Year:")
    val year = read.nextInt()

    val msg = if(checkLeapYear(year)) {
        "Given year is a leap year."
    } else {
        "Given year is not a leap year."
    }

    println(msg)
}

/**
 * Function that check whether given year is leap year or not.
 */
private fun checkLeapYear(year: Int): Boolean {
    return when {
        ((year % 400 == 0) ||  (((year % 4) == 0) && ((year % 100) != 0))) -> true
        else -> false
    }
}

When you run the program, output will be

Enter Year:
2021
Given year is not a leap year.

Here, we have created an object of Scanner. Scanner takes an argument which says where to take input from.
System.`in` means take input from standard input – Keyboard.

read.nextIn() means read anything entered by user before space or line break from standard input – Keyboard.
Input read by scanner is then stored in variable year

checkLeapYear checks whether given year is leap year or not. If yes, it returns true. Otherwise, it returns false.
Note: We have used when expression in this example just to show how to use when expression in this case.

Finally, we print result value using println() method.

Leave a Reply