Java Relational Operators
In this page:
Equality and Inequality
== tests whether two primitive values are exactly equal, and != tests whether they differ -- both always produce a boolean result you can use directly in a condition.
Example: Equality and Inequality
public class Main {
public static void main(String[] args) {
int a = 5, b = 5;
System.out.println(a == b); // true
System.out.println(a != b); // false
}
}
Login to try C/C++/Java/PHP code in the editor
Greater Than and Less Than
> and < compare magnitude between two numeric values and return true or false accordingly; they only work on primitives, not on objects like String, which don't have a natural numeric ordering.
Example: Greater Than and Less Than
public class Main {
public static void main(String[] args) {
System.out.println(7 > 3); // true
System.out.println(7 < 3); // false
}
}
Login to try C/C++/Java/PHP code in the editor
Greater Than or Equal to and Less Than or Equal to
>= and <= work like their strict counterparts but also return true when the two values are exactly equal, which matters for boundary conditions like checking if an age qualifies as 18 or older.
Example: Greater Than or Equal to and Less Than or Equal to
public class Main {
public static void main(String[] args) {
int age = 18;
System.out.println(age >= 18); // true - boundary included
System.out.println(age <= 17); // false
}
}
Login to try C/C++/Java/PHP code in the editor
Comparing Objects
For objects, == compares whether two variables point to the exact same object in memory, not whether their contents match -- two separate String objects holding "hello" will compare as unequal with ==, so you need .equals() to compare their actual characters.
Example: Comparing Objects
public class Main {
public static void main(String[] args) {
String a = new String("hello");
String b = new String("hello");
System.out.println(a == b); // false - different objects in memory
System.out.println(a.equals(b)); // true - same content
}
}
Login to try C/C++/Java/PHP code in the editor
Using Relational Operators in Conditions
Relational operators are what give an if statement's condition its boolean value in the first place, so combining them with logical operators (&&, ||) is how you express multi-part decision logic.
Example: Using Relational Operators in Conditions
public class Main {
public static void main(String[] args) {
int age = 20;
int score = 85;
if (age >= 18 && score > 80) { // relational + logical combined
System.out.println("Eligible");
}
}
}
Login to try C/C++/Java/PHP code in the editor
Chapter Quiz — Complete all 9 topics to unlock
0/9 topics done
Complete these topics first: