English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
Comprehensive Collection of Kotlin Examples
In this program, you will learn to use if else and when statements in Kotlin to find the largest number among three numbers.
fun main(args: Array<String>) { val n1 = -4.5 val n2 = 3.9 val n3 = 2.5 if (n1 >= n2 && n1 >= n3) println("$n1 is the largest number.") else if (n2 >= n1 && n2 >= n3) println("$n2 is the largest number.") else println("$n3 is the largest number.") }
When running the program, the output is:
3.9 is the largest number.
In the above program, three numbers-4.5,3.9and2.5are stored in variables n1, n2and n3in.
Then, to find the largest number, use if else statements to check the following conditions
if n1is greater than or equal to n2and n3, n1is the largest.
if n2is greater than or equal to n1and n3, n2is the largest.
otherwise, n3is the largest.
You can also find the largest number using the when statement.
This is the equivalent Java code:Java program to find the largest number among three
fun main(args: Array<String>) { val n1 = -4.5 val n2 = 3.9 val n3 = 5.5 when { n1 >= n2 && n1 >= n3 -> println("$n1 is the largest number.") n2 >= n1 && n2 >= n3 -> println("$n2 is the largest number.") else -> println("$n3 is the largest number.") } }
When running the program, the output is:
5.5 is the largest number.
In the above program, we use the when statement instead of the if..else if..else block.
Therefore, the above conditions are the same in the two programs.