In this chapter you will learn:
- What is relational operator in Java?
- What is the symbol of relational operator?
- What does relational operator do?
- Programming example of relational operator in Java
What is relational operator in Java?
Relational operator is the operator which compares two operands to check whether it is equal, greater than, less than or not equal to another operands.
Operator | Description | Example |
== | equal to: compare two operands and check whether it is equal | num1 == num2 |
!= | not equal to: compare two operands and check whether it is not equal | num1 != num2 |
> | greater than: compare two operands and check whether left operand is greater than right operand | num1 > num2 |
>= | greater than or equal to: compare two operands and check whether left operand is greater than or equal to right operand | num1 >= num2 |
< | less than: compare two operands and check whether left operand is lesser than right operand | num1 < num2 |
<= | less than or equal to: compare two operands and check whether left operand is lesser than or equal to right operand | num1 <= num2 |
What does relational operator do?
You can say relational operator is comparative operator. When you have two operands and you need to check whether it is equal or not, you need equal to (==) relational operator. Relational operator is mostly used with IF conditional constructs and returns Boolean value (true or false).
Programming Example:
class RelationalOperator { public static void main(String[] args) { int num1, num2; num1=20; num2=30; if(num1==num2) { System.out.println("num1 is equal to num2"); } if(num1!=num2) { System.out.println("num1 is not equal to num2"); } if(num1<num2) {="" system.out.println("num1="" is="" less="" than="" num2");="" }="" if(num1="">num2) { System.out.println("num1 is greater than num2"); } } }
Output
D:\JavaProgram>javac RelationalOperator.java
D:\JavaProgram>java RelationalOperator
num1 is not equal to num2
num1 is less than num2
D:\JavaProgram> __
Summary
In this chapter you have learned what relational operator, their symbol is and how they work. You have also seen a complete programming example demonstrating relational operator. In the next chapter you will learn about logical operator in java.