Skip to main content

Relational Operators

Java provides several operators to compare variables. These are known as relational operators, also referred to as comparison operators. In this article, we will discuss each of these operators in detail and show you how to use them correctly.

What are Relational Operators?

Relational operators are used to compare two values. The result of a comparison is a boolean value, either true or false. Java provides six relational operators:

  1. == (Equal to)
  2. != (Not equal to)
  3. < (Less than)
  4. > (Greater than)
  5. <= (Less than or equal to)
  6. >= (Greater than or equal to)

Let's learn more about each of them.

== (Equal to)

The == operator checks if the two values are equal. If they are equal, it returns true. Otherwise, it returns false.

int a = 5;
int b = 5;
System.out.println(a == b); // Prints: true

!= (Not Equal to)

The != operator checks if the two values are not equal. If they are not equal, it returns true. Otherwise, it returns false.

int a = 5;
int b = 4;
System.out.println(a != b); // Prints: true

< (Less Than)

The < operator checks if the value of the left operand is less than the value of the right operand. If it is, the operator returns true. Otherwise, it returns false.

int a = 4;
int b = 5;
System.out.println(a < b); // Prints: true

> (Greater Than)

The > operator checks if the value of the left operand is greater than the value of the right operand. If it is, the operator returns true. Otherwise, it returns false.

int a = 5;
int b = 4;
System.out.println(a > b); // Prints: true

<= (Less Than or Equal To)

The <= operator checks if the value of the left operand is less than or equal to the value of the right operand. If it is, the operator returns true. Otherwise, it returns false.

int a = 5;
int b = 5;
System.out.println(a <= b); // Prints: true

>= (Greater Than or Equal To)

The >= operator checks if the value of the left operand is greater than or equal to the value of the right operand. If it is, the operator returns true. Otherwise, it returns false.

int a = 5;
int b = 4;
System.out.println(a >= b); // Prints: true

Summary

Relational operators are an essential part of Java. They allow us to make comparisons between values and make decisions based on those comparisons. Keep practicing with these operators, and soon you'll find them easy to use.

Always remember that the result of a comparison using relational operators is a boolean value (true or false). This will be very useful when we start discussing conditional statements in future lessons.

Happy coding!