Java relational operator
Relational Operators in Java Programming :
- Relational Operators are used to check relation between two variables or numbers.
- Relational Operators are Binary Operators.
- Relational Operators returns “Boolean” value .i.e it will return true or false.
- Most of the relational operators are used in “If statement” and inside Looping statement in order to check truthness or falseness of condition.
We can use Relational Operators in multiple ways -
- Inside Condition for checking whether condition is true or false.
- Inside Expression.
Operator | Result |
---|---|
== | Equal to |
!= | Not equal to |
> | Greater than |
< | Less than |
>= | Greater than or equal to |
<= | Less than or equal to |
Live Example 1 : Comparison Operator Demo
class ComparisonDemo { public static void main(String[] args){ int ivar1 = 1; int ivar2 = 2; if(ivar1 == ivar2) System.out.println("ivar1 == ivar2"); if(ivar1 != ivar2) System.out.println("ivar1 != ivar2"); if(ivar1 > ivar2) System.out.println("ivar1 > ivar2"); if(ivar1 < ivar2) System.out.println("ivar1 < ivar2"); if(ivar1 <= ivar2) System.out.println("ivar1 <= ivar2"); } }
Output :
ivar1 != ivar2 ivar1 < ivar2 ivar1 <= ivar2
Some Must Remember Notes : Be aware of it
1 . Do not Use Relational Operator to Initialize Non-Boolean Variable
Consider Following Program -
class boolDemo { public static void main(String args[]) { int num1 = 100 > 20; System.out.println(num1); } }
In this situation , we cannot use relational operator in the expression like C Programming If you are coming from C/C++ background then you must throw your habit of using relational operator inside expression.
Following Code will run -
However we can use Relational Operators in Expression in which final result will be accumulated in boolean variable.
class boolDemo { public static void main(String args[]) { boolean num1 = 100 > 20; System.out.println(num1); } }
Output :
true
2 . Do not use just variable name of non-boolean data type inside if
class boolDemo { public static void main(String args[]) { boolean num1 = true; if(num1) { System.out.println(num1); } } }
Output :
true
however if you try this following program then you will definitely get an error -
class boolDemo { public static void main(String args[]) { int num1 = 10; if(num1) { System.out.println(num1); } } }
Output :
C:code>javac hello.java hello.java:7: incompatible types found : int required: boolean if(num1) ^ 1 error
Conclusion :
- If you are using Relational Operator in expression then use “Boolean” Variable at Left hand side.