Relational operators usage for data comparison
Use of equality check operator == and other relational operators like not equal to !=, less than < , greater than > , less than or equal to <= and greater than or equal to >= operators.
Learning Objectives
- Understanding the use of six relational operators for equality and other comparison purposes.
Source Code
|
Run Output
Code Understanding
int a=10,b=10; //integer variables a and b are initialised with 10
boolean c= (a==b);
Since relational operators result in true or false so we shall use a boolean variable c to store the comparison result. Here we made a equality comparison.
System.out.println(“a=10,b=10 so a==b will be “+c);
Since both values are same equality comparison will result in true
c=a!=b; System.out.println(“a=10,b=10 so a!=b will be “+c);
For the same variables being same not equal to will result in false
c=a>5; System.out.println(“a=10 so a>5 will be “+c);
Variable a is set as 10 so its comparison of greater than 5 will result in true
c=b<11; System.out.println(“b=10 so b<11 will be “+c);
Variable b is set as 10 so its comparison of lesser than 11 will result in true
c=a<=10;System.out.println(“a=10 so a<=10 will be “+c);
Variable a is set as 10 so its comparison of lesser than or equal to 10 will result in true
c=b>=10;System.out.println(“b=10 so a>=10 will be “+c);
Variable b is set as 10 so its comparison of greater than or equal to 10 will result in true
Notes
- Some people prefer to call the relational operators as comparison operators.
- The reference document of relational operators can be seen at
https://docs.oracle.com/javase/tutorial/java/nutsandbolts/op2.html
Common Errors
- Some students have problem in remembering the < and > than sign usage. Just a small tip for them. Remember that Hungry Alligator’s mouth simile. The hungry mouth always opens towards the bigger chunk. If 3 < 5 then mouth seems to open towards 5 so 5 is bigger. Since we read from left to right we will say 3 is smaller or lesser than 5. So the symbol will be called less than. Some people remember it by Less than means Left side is pinched.
Suggested Filename(s): RelationalOP.java
sunmitra| Created: 3-Mar-2018 | Updated: 3-Mar-2018|