Kotlin. Comparison operators. Logical operators

Comparison operators (>, <, >=, <= …). Logical operators (&&, ||, !)


Contents


Search other resources:

1. Comparison operators. The purpose. Comparing values and object references

To compare two values, the Kotlin language uses comparison operators. These operators are binary. This means they require two operands on the left and right sides. The result of any comparison operator is a Boolean value true or false.

Comparison operators have the same syntax and purpose as in many other languages. These operators include the following:

  • < – compares two values and determines if the value on the left side of the operator is less than the value on the right side. If this fact is confirmed, then true is returned;
  • > – determines whether the value on the left side of the operator is greater than the value on the right side;
  • <= – determines whether the value on the left is less than or equal to the value on the right;
  • >= – determines if the value on the left is greater than or equal to the value on the right;
  • == – evaluates whether the value on the left is equal to the value on the right;
  • != – evaluates whether the value on the left is not equal to the value on the right;
  • === – determines whether two references refer to the same object (Figure 1);
  • !== – determines whether two references not refer to the same object (Figure 2).

From the above list, the last two operators ===, !== compare the values of references to objects, not the values of these objects (see Figures 1, 2).

Kotlin. Operators ===, !===. A reference to the same object

Figure 1. The case when references point to one object. The === operator returns true, the !== operator returns false

Kotlin. Operators ===, !==. A reference to different objects

Figure 2. The case when the references point to different objects. Operator === returns false, operator !== returns true

 

2. An example of operators for comparing values of variables of different types

 

fun main(args:Array<String>)
{
  // Comparison operators >, <, >=, <=, ==, !=
  // Determination of equality of values of variables of different types
  // 1. Comparing values of integer types
  val a : Int = 25
  val b : Int = 30
  var res1 : Boolean = a > b // res1 = false
  println("a > b => " + res1)

  res1 = a <= b // res1 = true
  println("a <= b => " + res1)

  // 2. Comparing values of floating point types
  val x : Double = 2.85
  val y = x
  var res2 = x == y // operator ==
  println("x == y => " + res2)

  // in the if statement
  if (x != 3.5) // operator !=
    println("x != 3.5")
  else
    println("x == 3.5")

  res2 = x < 0   // operator <
  println("x < 0 => " + res2)

  // 3. Comparison of values of type Char
  val c1 : Char = 'z'
  var res3 : Boolean

  res3 = c1 > 'a'

  if (res3)
    println("z > a")
  else
    println("z < a")

  // 4. Comparison values of type String
  val s1 = "abcd"
  val s2 = "abcde"
  var res4 = s1 != s2
  println("\'abcd\' != \'abcde\' => " + res4)

  res4 = s1 < s2
  println("\'abcd\' < \'abcde\' => " + res4)
}

The result of the program

a > b => false
a <= b => true
x == y => true
x != 3.5
x < 0 => false
z > a
'abcd' != 'abcde' => true
'abcd' < 'abcde' => true

 

3. An example demonstrating the use of reference comparison operators (===, !==)

 

// A class with a function
class A
{
  fun Hello()
  {
    println("Hello world!")
  }
}

fun main(args:Array<String>)
{
  // Comparison operators ===, !==
  // Determining if two references point to the same object

  // 1. References ref1, ref2 point to the same object (instance)
  val ref1 = A()
  val ref2 = ref1 // assignment of references values

  // Operator ===
  if (ref1 === ref2)
    println("ref1 === ref2")

  // Operator !==
  if (ref1 !== ref2)
    println("ref1 !== ref2")

  // 2. References ref3, ref4 point to different objects
  val ref3 = A()
  val ref4 = A()

  // Operator ===
  if (ref3 === ref4)
    println("ref3 === ref4") // will not be executed

  // Operator !==
  if (ref3!==ref4)
    println("ref3 !== ref4") // will be executed
}

The result of the program

ref1 === ref2
ref3 !== ref4

 

4. Logical operators (&&, ||, !). List. The purpose

Logical operators allow you to build complex logical expressions bypassing a large (unnecessary) number of conditional jump operators in the algorithm for solving the problem.

The result of a boolean operator is the Boolean value true or false. A sequence of logical operators, combined by operands, forms a logical expression.

Using a Boolean expression, you can shorten your code and improve its visualization.

For example, if a program needs to perform one single action (sequence of statements) when various conditions are met

if (condition1) statement
if (condition2) statement
...
if (conditionN) statement

then it is more expedient to use the logical operator || according to the sample below

if (condition1 || condition2 || ... || conditionN)
  statement

The following logical operators are defined in the Kotlin language

  • && – logical AND. It is a binary operator (requires two operands left and right). The && operator returns true if the value of both operands is true. Otherwise, false is returned;
  • || – logical OR. This is a binary operator. Operator || returns false if the value of both operands is false. Otherwise, the operator returns true;
  • ! – logical negation NOT. This is a unary operator, returns true if the operand value is false. Otherwise, false is returned.

 

5. Examples of using the logical operators &&, ||, ! in conditional expressions
5.1. Determining a pair of identical numbers

Task. Given three real numbers a, b, c. Determine if there is at least one pair of equal numbers among them.

Solution.

 

fun main(args:Array<String>)
{
  // Determining a pair of equal numbers
  // 1. Declaring variables
  val a : Double
  val b : Double
  val c : Double

  // 2. Input values
  print("a = ")
  a = readLine().toString().toDouble()
  print("b = ")
  b = readLine().toString().toDouble()
  print("c = ")
  c = readLine().toString().toDouble()

  // 3. Calculation using the operator - logical OR  
  if ((a==b) || (a==c) || (b==c))
    println("Yes")
  else
    println("No")
}

The result of the program

a = 3.8
b = 2.2
c = 3.8
Yes

 

5.2. Determination of the presence of the specified digit in a number

Task.

A two-digit number is given. Determine if the number 7 is included in it.

Solution.

fun main(args:Array<String>)
{
  // Determining the occurrence of a given digit in a number
  // 1. Declaring variables
  val number : Int

  // 2. Input values
  print("number = ")
  number = readLine().toString().toInt()

  // 3. Checking the correctness of the entered data
  if ((number<10) || (number>99))
  {
    println("Incorrect input.")
    return
  }

  // 4. Calculation
  // Get the first and second digits of a two-digit number
  if ((number/10==7) || (number%10==7))
    println("Yes") // number 7 is in the number
  else
    println("No")
}

Test example

number = 71
Yes

 

5.3. Determining the presence of two digits in a number

Task.

A three-digit number is specified. Determine if it contains numbers 4 and 6 at the same time.

Solution.

 

fun main(args:Array<String>)
{
  // Determining the occurrence of two given digits in a number
  // 1. Declaring variables
  val number : Int   // specified number

  // 2. Input values
  print("number = ")
  number = readLine().toString().toInt()

  // 3. Checking the correctness of the entered data
  if ((number<100) || (number>999))
  {
    println("Incorrect input.")
    return
  }

  // 4. Calculation
  // Highlight the first, second and third digits of a three-digit number
  val digit1 : Int = number/100
  val digit2 : Int = (number/10)%10
  val digit3 : Int = number%10

  if ((digit1==6)&&(digit2==4) || (digit1==4)&&(digit2==6))
    println("Yes")
  else
  if ((digit1==6)&&(digit3==4) || (digit1==4)&&(digit3==6))
    println("Yes")
  else
  if ((digit2==6)&&(digit3==4) || (digit2==4)&&(digit3==6))
    println("Yes")
  else
    println("No")
}

Test example

number = 624
Yes

 

5.4. Determining whether a number belongs to a given range

Task.

Determine if the given number belongs to the range [a; b]. Solve the task using the negation operator ! (NOT).

Solution.

fun main(args:Array<String>)
{
  // Determining whether a number belongs to a given range
  // 1. Declaring variables
  val number : Int   // given number
  val a : Int // lower limit
  val b : Int // upper limit

  // 2. Input values
  print("number = ")
  number = readLine().toString().toInt()
  print("a = ")
  a = readLine().toString().toInt()
  print("b = ")
  b = readLine().toString().toInt()

  // 3. Checking the correctness of the entered data
  if (a>b)
  {
    print("Incorrect input.")
    return
  }

  // 4. Calculation
  // negation is used! (NOT)
  if (!((number>=a)&&(number<=b)))
    print("No") // out of range
  else
    print("Yes") // within range
}

Test example

number = 24
a = 35
b = 77
No

 


Related topics