List of relational operators
Kotlin provides six relational operators to compare numbers:
==
(equal to)!=
(not equal to)>
(greater than)>=
(greater than or equal to)<
(less than)<=
(less than or equal to)
The result of applying a relational operator to its operands takes the Boolean type (true
or false
) regardless of the types of operands.
Comparing integer numbers
Relational operators allow you to easily compare, among other things, two integer numbers. Here are some examples:
val one = 1
val two = 2
val three = 3
val four = 4
val oneIsOne = one == one // true
val res1 = two <= three // true
val res2 = two != four // true
val res3 = two > four // false
val res4 = one == three // false
Relational operators can be used in mixed expressions together with arithmetic operators. In such expressions, relational operators have a priority than arithmetic operators.
In the following example, first two sums will be calculated, and then they will be compared using the operator >
.
val number = 1000val result = number + 10 > number + 9 // 1010 > 1009 is true
The result
is true
.
Joining relational operations using logical operators
a <= b <= c
Instead, you should join two Boolean expressions using logical operators like ||
and &&
.
For example, let's say we'd like to check the validity of the following expression:
100 < number < 200
To do that, we should write something like this:
number > 100 && number < 200
(number > 100) && (number < 200)
As a more complex example, let's consider a program that reads an integer number and checks if the number belongs to the range [100; 200], including 100 and 200 in the range.
import java.util.*
fun main(args: Array<String>) {
val scanner = Scanner(System.`in`)
val left = 100
val right = 200
val number = scanner.nextInt()
val inRange = number >= left && number <= right // joining two expressions using AND
println(inRange)
}