← Back to Core Java Course | Chapter 3: Operators | Lesson 3 of 9

Java Relational Operators

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

java
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
	}
}

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

java
public class Main {
	public static void main(String[] args) {
		System.out.println(7 > 3);  // true
		System.out.println(7 < 3);  // false
	}
}

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

java
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
	}
}

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

java
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
	}
}

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

java
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 run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.