English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
Comprehensive Collection of Kotlin Examples
In this program, you will learn to check if a given number is positive or negative. This can be done by using if in Kotlin-or when expressions to complete.
To check if a number is positive or negative, compare it with 0.
If the number is greater than zero, it is positive.
If the number is less than zero, it is negative.
If the number is equal to zero, it is zero.
fun main(args: Array<String>) { val number = 12.3 if (number < 0.0) println("$number is negative.") else if (number > 0.0) println("$number is positive.") else println("$number is 0.") }
When running the program, the output is:
12.3 It is positive.
This is the equivalent Java code:Java program to check if a number is positive or negative.
The if else statements in the above program can also be replaced with the when expression.
fun main(args: Array<String>) { val number = -12.3 when { number < 0.0 -> println("$number 是负数.") number > 0.0 -> println("$number 是正数.") else -> println("$number 为 0.") } }
When running the program, the output is:
-12.3 Is a Negative Number.