List of relational operators
Java provides six relational operators to compare numbers:
==
(equal to)!=
(not equal to)>
(greater than)>=
(greater than or equal to)<
(less than)<=
(less than or equal to)
The result of applying a relational operator to its operands takes the boolean type (true
or false
) regardless of the types of operands.
Comparing integer numbers
Relational operators allow you to easily compare, among other things, two integer numbers. Here are some examples below:
int one = 1;
int two = 2;
int three = 3;
int four = 4;
boolean oneIsOne = one == one; // true
boolean res1 = two <= three; // true
boolean res2 = two != four; // true
boolean res3 = two > four; // false
boolean res4 = one == three; // false
Relational operators can be used in mixed expressions together with arithmetic operators. In such expressions, relational operators have a priority than arithmetic operators.
In the following example, first of all, two sums are be calculated, and then they are compared using the operator >
.
int number = 1000;boolean result = number + 10 > number + 9; // 1010 > 1009 is true
The result
is true
.
Joining relational operations using logical operators
||
and &&
.Here is an example:
number > 100 && number < 200; // it means 100 < number < 200
(number > 100) && (number < 200);
Here is a more general example of variables.
int number = ... // it has a value
int low = 100, high = 200; // borders
boolean inRange = number > low && number < high; // joining two expressions using AND.
number
belongs to a range.An example of a program
h1
, h2
, h3
and then check that h1 >= h2
and h2 >= h3
. Note, h means the height of a boy.import java.util.Scanner;
public class CheckAscOrder {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int h1 = scanner.nextInt();
int h2 = scanner.nextInt();
int h3 = scanner.nextInt();
boolean ascOrdered = (h1 >= h2) && (h2 >= h3);
System.out.println(ascOrdered);
}
}
There are several input-output pairs:
Input 1
185 178 172
Output 1
true
Input 2
181 184 177
Output 2
false
It is possible not to use an additional variable to store the boolean result before output:
System.out.println((h1 >= h2) && (h2 >= h3));
But when your condition is quite long, it is hard to understand what does the code do without some explanations. A variable with a good name provides such an explanation.