Comparison operators are used to compare two values and determine if they are equal, greater than, or less than each other. In Java, there are several comparison operators:
Operator | Meaning | Example | Description |
= = | Equal | a == b | Checks if a is equal to b |
!= | Not equal | a!=b | Checks if a is not equal to b |
< | Less than | a<b | Checks if a is less than b |
> | Greater than | a>b | Checks if a is greater than b |
<= | Less than or equal | a<=b | Checks if a is less than or equal to b |
>= | Greater than or equal | a>= | Checks if a is greater than or equal to b |
==
: This operator is used to determine if two values are equal to each other. For example:
int a = 5;
int b = 5;
if (a == b) {
System.out.println("a and b are equal");
}
!=
: This operator is used to determine if two values are not equal to each other. For example:
int a = 5;
int b = 6;
if (a != b) {
System.out.println("a and b are not equal");
}
>
: This operator is used to determine if one value is greater than another. For example:
int a = 5;
int b = 6;
if (a > b) {
System.out.println("a is greater than b");
}
<
: This operator is used to determine if one value is less than another. For example:
int a = 5;
int b = 6;
if (a < b) {
System.out.println("a is less than b");
}
>=
: This operator is used to determine if one value is greater than or equal to another. For example:
int a = 5;
int b = 5;
if (a >= b) {
System.out.println("a is greater than or equal to b");
}
<=
: This operator is used to determine if one value is less than or equal to another. For example:
int a = 5;
int b = 5;
if (a <= b) {
System.out.println("a is less than or equal to b");
}
It is important to note that comparison operators can only be used with certain data types, such as int
, double
, char
, and boolean
. They cannot be used with reference types, like String
. To compare strings in Java, you can use the .equals()
method. For example:
String str1 = "Hello";
String str2 = "Hello";
if (str1.equals(str2)) {
System.out.println("str1 and str2 are equal");
}
Comparison operators are a fundamental part of programming and are used in many different contexts, including decision making and looping. Understanding how to use these operators is an essential skill for any Java programmer.