Home Java Java - Relational Operators
Java - Relational Operators
Java relational operators are used to compare two values. These operators return a
boolean result: true if the condition is met and false otherwise. Relational operators are
commonly used in decision-making statements like if conditions and loops.
Java provides several relational operators that can be applied to primitive data types such
as int, float, double, and char. These operators help determine equality, inequality, and
relative comparison between values.
List of Java Relational Operators
The following table lists the relational operators in Java:
Operator Description Example
(A == B) returns false if A
== (equal to) Checks if two values are equal.
is not equal to B.
(A != B) returns true if A is
!= (not equal to) Checks if two values are not equal.
not equal to B.
Checks if the left operand is greater than (A > B) returns true if A is
> (greater than)
the right operand. greater than B.
Checks if the left operand is smaller than (A < B) returns true if A is
< (less than)
the right operand. less than B.
>= (greater than or Checks if the left operand is greater than or (A >= B) returns true if A is
equal to) equal to the right operand. greater than or equal to B.
<= (less than or equal Checks if the left operand is smaller than or (A <= B) returns true if A is
to) equal to the right operand. less than or equal to B.
The following programs are simple examples which demonstrate the relational operators.
Copy and paste the following Java programs as [Link] file, and compile and run the
programs −
Example 1
In this example, we're creating two variables a and b and using relational operators.
We've performed equality and non-equality checks and printed the results.
public class Test {
public static void main(String args[]) {
int a = 10;
int b = 20;
[Link]("a == b = " + (a == b) );
[Link]("a != b = " + (a != b) );
}
}
Output
a == b = false
a != b = true
Example 2
In this example, we're creating two variables a and b and using relational operators.
We've performed greater than and less than checks and printed the results.
public class Test {
public static void main(String args[]) {
int a = 10;
int b = 20;
[Link]("a > b = " + (a > b) );
[Link]("a < b = " + (a < b) );
}
}
Output
a > b = false
a < b = true
Example 3
In this example, we're creating two variables a and b and using relational operators.
We've performed greater than or equal to and less than or equal to checks and printed the
results.
public class Test {
public static void main(String args[]) {
int a = 10;
int b = 20;
[Link]("b >= a = " + (b >= a) );
[Link]("b <= a = " + (b <= a) );
}
}
Output
b >= a = true
b <= a = false