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.
The following table lists the relational operators in Java:
Operator Description Example == (equal to) Checks if two values are equal.(A == B)
returns false
if A is not equal to B. != (not equal to) Checks if two values are not equal. (A != B)
returns true
if A is not equal to B. > (greater than) Checks if the left operand is greater than the right operand. (A > B)
returns true
if A is greater than B. < (less than) Checks if the left operand is smaller than the right operand. (A < B)
returns true
if A is less than B. >= (greater than or equal to) Checks if the left operand is greater than or equal to the right operand. (A >= B)
returns true
if A is greater than or equal to B. <= (less than or equal to) Checks if the left operand is smaller than or equal to the right operand. (A <= B)
returns true
if A is 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 Test.java file, and compile and run the programs −
Example 1In 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; System.out.println("a == b = " + (a == b) ); System.out.println("a != b = " + (a != b) ); } }Output
a == b = false a != b = trueExample 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; System.out.println("a > b = " + (a > b) ); System.out.println("a < b = " + (a < b) ); } }Output
a > b = false a < b = trueExample 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; System.out.println("b >= a = " + (b >= a) ); System.out.println("b <= a = " + (b <= a) ); } }Output
b >= a = true b <= a = false
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4