Scala - Relational Operators Example

1. Introduction

Relational operators are used to compare two values or expressions. These operators evaluate to a Boolean, indicating whether the comparison is true or false. Scala, being a statically typed language, supports standard relational operators that allow us to make comparisons between values. This blog post will go over Scala's relational operators.

Scala - Relational Operators

Scala provides the following relational operators, which are similar to those in other programming languages:

== (Equal to): Checks if the values of two operands are equal.

!= (Not equal to): Checks if the values of two operands are not equal.

> (Greater than): Checks if the value of the left operand is greater than the right operand.

< (Less than): Checks if the value of the left operand is less than the right operand.

>= (Greater than or equal to): Checks if the left operand is greater than or equal to the right operand.

<= (Less than or equal to): Checks if the left operand is less than or equal to the right operand.

2. Program Steps

1. Define variables for comparison.

2. Use relational operators to compare these variables.

3. Print the results of the comparisons.

4. Execute the program to see the output of the relational operations.

3. Code Program

object RelationalOperatorsDemo extends App {
  val a: Int = 10
  val b: Int = 20

  // Equal to
  println(s"$a == $b: " + (a == b))
  // Not equal to
  println(s"$a != $b: " + (a != b))
  // Greater than
  println(s"$a > $b: " + (a > b))
  // Less than
  println(s"$a < $b: " + (a < b))
  // Greater than or equal to
  println(s"$a >= $b: " + (a >= b))
  // Less than or equal to
  println(s"$a <= $b: " + (a <= b))
}

Output:

10 == 20: false
10 != 20: true
10 > 20: false
10 < 20: true
10 >= 20: false
10 <= 20: true

Explanation:

1. Two integer variables a and b are declared with values 10 and 20 respectively.

2. The relational operators ==, !=, >, <, >=, and <= are used to compare a and b.

3. Each comparison operation evaluates to a Boolean value true or false, which is printed to the console alongside the operation being performed.

4. The output demonstrates the results of each relational comparison. For instance, 10 == 20 is false because 10 is not equal to 20, whereas 10 < 20 is true because 10 is less than 20.


Comments