Using Relational and Equality Operators in Java
Course: Core Java Training
Topic: Using Relational and Equality Operators
Course Link: Core Java Training Course
Demo Link: Register for a Course Demo
Academy Website: JustAcademy
1. Introduction to Relational and Equality Operators
Relational and equality operators are important parts of Java programming because they allow developers to compare values and determine whether particular conditions are true or false. These operators are commonly used in decision-making statements, loops, validation logic, searching, sorting, and business rules.
For example, an application may compare a student's marks with the passing score, check whether an employee's salary is above a specified amount, or determine whether two numbers are equal.
Java comparison expressions generally return a Boolean result: true or false. This result can be used directly in an if statement or combined with other conditions.
Learning Objectives
- Understand the difference between relational and equality operators.
- Learn how to use
>, <, >=, and <=.
- Understand the equality operators
== and !=.
- Learn how comparison operators work with numeric and Boolean values.
- Understand the difference between comparing primitive values and object references.
- Use comparison operators in conditional statements and practical Java programs.
- Identify common mistakes involving comparisons and floating-point values.
2. What Are Relational Operators?
Relational operators compare two compatible numeric values to determine the relationship between them. They can check whether one number is greater than, less than, greater than or equal to, or less than or equal to another number.
The result of a relational comparison is always a Boolean value.
List of Relational Operators
| Operator |
Name |
Meaning |
Example |
Result |
> |
Greater than |
Checks whether the left value is greater than the right value. |
10 > 5 |
true |
< |
Less than |
Checks whether the left value is less than the right value. |
3 < 8 |
true |
>= |
Greater than or equal to |
Checks whether the left value is greater than or equal to the right value. |
10 >= 10 |
true |
<= |
Less than or equal to |
Checks whether the left value is less than or equal to the right value. |
4 <= 6 |
true |
3. Greater Than Operator (>)
The greater than operator checks whether the left operand has a value strictly greater than the right operand. If the left value is larger, the expression returns true; otherwise, it returns false.
Example
public class GreaterThanExample {
public static void main(String[] args) {
int a = 20;
int b = 10;
System.out.println(a > b);
System.out.println(b > a);
System.out.println(a > 20);
}
}
Output:
true
false
false
Explanation
20 > 10 returns true because 20 is greater than 10.
10 > 20 returns false because 10 is smaller than 20.
20 > 20 returns false because both values are equal, not strictly greater.
Practical Example: Checking Eligibility by Age
public class AgeEligibility {
public static void main(String[] args) {
int age = 21;
if (age > 18) {
System.out.println("Age is greater than 18.");
} else {
System.out.println("Age is 18 or below.");
}
}
}
Output:
Age is greater than 18.
The condition age > 18 evaluates to true when the age is greater than 18. If the requirement includes people who are exactly 18, the greater than or equal to operator should be used instead.
4. Less Than Operator (<)
The less than operator checks whether the left operand is strictly smaller than the right operand.
Example
public class LessThanExample {
public static void main(String[] args) {
int temperature = 15;
int limit = 20;
System.out.println(temperature < limit);
System.out.println(limit < temperature);
}
}
Output:
true
false
Practical Example: Checking Stock Availability
public class StockCheck {
public static void main(String[] args) {
int stock = 4;
int minimumStock = 10;
if (stock < minimumStock) {
System.out.println("Stock is below the minimum level.");
} else {
System.out.println("Stock level is sufficient.");
}
}
}
Output:
Stock is below the minimum level.
This type of comparison is useful for inventory management, warning systems, temperature monitoring, and resource allocation.
5. Greater Than or Equal To Operator (>=)
The greater than or equal to operator returns true when the left operand is either greater than or equal to the right operand. Unlike >, it includes the case where both values are equal.
Example
public class GreaterThanOrEqualExample {
public static void main(String[] args) {
int marks = 40;
int passingMarks = 40;
System.out.println(marks >= passingMarks);
}
}
Output:
true
Practical Example: Passing Marks
public class ExamResult {
public static void main(String[] args) {
int marks = 40;
int passingMarks = 40;
if (marks >= passingMarks) {
System.out.println("Student has passed.");
} else {
System.out.println("Student has failed.");
}
}
}
Output:
Student has passed.
This operator is useful when a minimum requirement must be met, such as minimum marks, a minimum account balance, or a minimum age.
6. Less Than or Equal To Operator (<=)
The less than or equal to operator returns true when the left operand is smaller than or equal to the right operand.
Example
public class LessThanOrEqualExample {
public static void main(String[] args) {
int currentItems = 5;
int maximumItems = 5;
System.out.println(currentItems <= maximumItems);
}
}
Output:
true
Practical Example: Checking a Spending Limit
public class SpendingLimit {
public static void main(String[] args) {
double expense = 450.00;
double budget = 500.00;
if (expense <= budget) {
System.out.println("Expense is within budget.");
} else {
System.out.println("Expense exceeds the budget.");
}
}
}
Output:
Expense is within budget.
The operator allows a value that exactly matches the limit. This makes it appropriate for inclusive upper-bound checks.
7. What Are Equality Operators?
Equality operators determine whether two values are equal or not equal. Java has two equality operators:
== — equal to.
!= — not equal to.
For primitive numeric values, these operators compare values. For Boolean values, they compare whether the truth values match. When used with object references, they compare whether the references point to the same object, rather than comparing the contents of the objects.
8. Equal To Operator (==)
The equality operator == returns true if the compared primitive values are equal. It returns false if they differ.
Example
public class EqualToExample {
public static void main(String[] args) {
int a = 25;
int b = 25;
int c = 30;
System.out.println(a == b);
System.out.println(a == c);
}
}
Output:
true
false
Explanation
a == b returns true because both variables contain 25.
a == c returns false because 25 and 30 are different values.
Practical Example: Checking a PIN
public class PinCheck {
public static void main(String[] args) {
int enteredPin = 1234;
int savedPin = 1234;
if (enteredPin == savedPin) {
System.out.println("PIN matches.");
} else {
System.out.println("PIN does not match.");
}
}
}
Output:
PIN matches.
This example demonstrates numeric comparison only. Real authentication systems should not store sensitive PINs as plain numbers or rely on a simple comparison as their complete security mechanism.
9. Not Equal To Operator (!=)
The not equal to operator returns true when the two compared values are different. If the values are equal, it returns false.
Example
public class NotEqualExample {
public static void main(String[] args) {
int first = 10;
int second = 20;
System.out.println(first != second);
System.out.println(first != 10);
}
}
Output:
true
false
Practical Example: Checking Whether a Number Is Not Zero
public class NonZeroCheck {
public static void main(String[] args) {
int divisor = 5;
if (divisor != 0) {
System.out.println("Division can be performed.");
} else {
System.out.println("Cannot divide by zero.");
}
}
}
Output:
Division can be performed.
The condition divisor != 0 is a common way to verify that an integer divisor is nonzero before performing integer division or remainder calculation.
10. Difference Between Relational and Equality Operators
| Feature |
Relational Operators |
Equality Operators |
| Operators |
>, <, >=, <= |
==, != |
| Main purpose |
Compare the relative size of numeric values. |
Check whether values are equal or different. |
| Result |
Boolean value: true or false. |
Boolean value: true or false. |
| Typical use |
Range checks, thresholds, limits, and ordering. |
Exact value checks and difference checks. |
| Example |
score >= 50 |
score == 50 |
| Object references |
Not used to order ordinary object references. |
== and != can compare reference identity. |
11. Difference Between = and ==
One of the most common beginner mistakes is confusing the assignment operator (=) with the equality operator (==).
| Operator |
Name |
Purpose |
Example |
= |
Assignment |
Assigns a value to a variable. |
int age = 20; |
== |
Equality |
Checks whether two comparable values are equal. |
age == 20 |
Example
public class AssignmentVsEquality {
public static void main(String[] args) {
int age = 20;
System.out.println(age == 20);
}
}
Output:
true
The statement int age = 20; assigns the value 20 to the variable. The expression age == 20 compares the value stored in age with 20 and produces a Boolean result.
12. Using Comparison Operators with If-Else Statements
Relational and equality operators are often used with if, else if, and else statements to control the flow of a program.
Example: Grading a Student
public class StudentGrade {
public static void main(String[] args) {
int marks = 82;
if (marks >= 90) {
System.out.println("Grade A");
} else if (marks >= 75) {
System.out.println("Grade B");
} else if (marks >= 50) {
System.out.println("Grade C");
} else {
System.out.println("Fail");
}
}
}
Output:
Grade B
The program evaluates each condition in sequence. Since 82 is not at least 90 but is at least 75, the second branch executes. Once a matching branch executes, the remaining branches are skipped.
13. Comparing Primitive Data Types
Primitive types include byte, short, int, long, float, double, char, and boolean. Numeric primitive values can be compared with suitable relational and equality operators. Boolean values support equality comparisons.
Comparing Integer Values
int a = 15;
int b = 25;
System.out.println(a < b);
System.out.println(a == b);
System.out.println(a != b);
Output:
true
false
true
Comparing Character Values
Java's char type represents a UTF-16 code unit. Character values can be compared numerically according to their code-unit values.
char first = 'A';
char second = 'B';
System.out.println(first < second);
System.out.println(first == second);
Output:
true
false
These comparisons use the underlying character values, not language-specific alphabetical sorting rules.
Comparing Boolean Values
Boolean values can be compared using == and !=. Relational operators such as > and < cannot be applied to Boolean values.
boolean isActive = true;
boolean isVerified = false;
System.out.println(isActive == true);
System.out.println(isActive != isVerified);
System.out.println(isVerified == false);
Output:
true
true
true
In real programs, a direct Boolean condition such as if (isActive) is usually clearer than if (isActive == true).
14. Comparing Floating-Point Values
Java's float and double types represent approximate binary floating-point numbers. Because many decimal fractions cannot be represented exactly, direct equality comparisons may produce unexpected results after arithmetic calculations.
Example
public class FloatingPointComparison {
public static void main(String[] args) {
double result = 0.1 + 0.2;
System.out.println(result);
System.out.println(result == 0.3);
}
}
Typical output:
0.30000000000000004
false
The computed value is not represented as exactly the same binary floating-point value as the literal 0.3.
Using a Tolerance for Approximate Comparisons
public class ToleranceComparison {
public static void main(String[] args) {
double result = 0.1 + 0.2;
double expected = 0.3;
double tolerance = 0.000001;
if (Math.abs(result - expected) < tolerance) {
System.out.println("Values are approximately equal.");
} else {
System.out.println("Values are different.");
}
}
}
Output:
Values are approximately equal.
The tolerance should be selected according to the scale and precision requirements of the calculation. This technique is useful for scientific calculations and measurements, but it is not a universal substitute for exact decimal arithmetic.
15. Comparing Strings: == Versus equals()
A particularly important concept in Java is the difference between comparing String references with == and comparing String contents with equals().
When applied to object references, == checks whether both references identify the same object. It does not generally check whether two String objects contain the same characters.
The equals() method of the String class compares the character contents of two strings.
Example
public class StringComparison {
public static void main(String[] args) {
String first = new String("Java");
String second = new String("Java");
System.out.println(first == second);
System.out.println(first.equals(second));
}
}
Output:
false
true
Explanation
first == second returns false because the two variables refer to distinct String objects.
first.equals(second) returns true because both strings contain the same text.
Safe String Comparison
String username = "admin";
if ("admin".equals(username)) {
System.out.println("Username matches.");
} else {
System.out.println("Username does not match.");
}
Output:
Username matches.
Calling equals() on a known non-null String literal avoids a NullPointerException if username is null. For case-insensitive comparisons, Java provides equalsIgnoreCase().
16. Comparing Objects and Null References
For ordinary object references, the operators == and != check reference identity. Two references are equal under == when they refer to the same object or when both are null.
public class ObjectReferenceComparison {
public static void main(String[] args) {
Object first = new Object();
Object second = first;
Object third = new Object();
System.out.println(first == second);
System.out.println(first == third);
System.out.println(first != third);
}
}
Output:
true
false
true
The variables first and second refer to the same object, while third refers to a different object.
If you need to compare the logical contents of custom objects, use an appropriately implemented equals() method. A class that overrides equals() should also follow the Java hashCode() contract.
17. Combining Comparisons with Logical Operators
Relational and equality expressions can be combined with logical operators to build more complex conditions.
&& means logical AND: both conditions must be true.
|| means logical OR: at least one condition must be true.
! means logical NOT: it reverses a Boolean result.
Example: Checking an Age Range
public class AgeRangeCheck {
public static void main(String[] args) {
int age = 25;
if (age >= 18 && age <= 60) {
System.out.println("Age is within the specified range.");
} else {
System.out.println("Age is outside the specified range.");
}
}
}
Output:
Age is within the specified range.
The condition is true only when the age is at least 18 and at most 60. Both boundary values are included.
Example: Checking a Discount Condition
public class DiscountEligibility {
public static void main(String[] args) {
double purchaseAmount = 1500.0;
boolean member = true;
if (purchaseAmount >= 1000 && member) {
System.out.println("Discount is available.");
} else {
System.out.println("Discount is not available.");
}
}
}
Output:
Discount is available.
Java's && and || operators use short-circuit evaluation: the second operand is evaluated only when necessary to determine the result. This can be useful for safe checks, such as verifying a reference is not null before calling a method on it.
18. Operator Precedence in Comparison Expressions
Java evaluates operators according to precedence rules. Relational operators such as > and < have higher precedence than equality operators == and !=. Logical AND has higher precedence than logical OR.
Example
int a = 10;
int b = 20;
int c = 30;
System.out.println(a < b == b < c);
Output:
true
The expression is evaluated as (a < b) == (b < c). Both relational comparisons return true, so the equality comparison also returns true.
Although Java allows this expression, separate comparisons or parentheses can improve readability when conditions become complicated.
Important Note: Chained Comparisons
Unlike some mathematical notation, Java does not allow a numeric chained comparison such as 10 < x < 20. The first comparison returns a Boolean value, and Java cannot compare that Boolean result to 20 using <.
Instead, write:
if (x > 10 && x < 20) {
System.out.println("x is between 10 and 20, excluding the limits.");
}
19. Common Mistakes and How to Avoid Them
| Mistake |
Problem |
Correct Approach |
Using = instead of == |
Assignment and comparison have different purposes. |
Use == when comparing primitive values for equality. |
Using > when equality should be accepted |
The boundary value returns false. |
Use >= when the boundary is included. |
Comparing String objects with == |
Reference identity is checked instead of text contents. |
Use equals() for content comparison. |
| Comparing floating-point calculations with exact equality |
Binary representation can produce small rounding differences. |
Use a suitable tolerance or an appropriate decimal representation. |
Writing a < b < c |
Java does not support chained numeric comparisons. |
Write a < b && b < c. |
| Ignoring null references |
Calling a method on a null reference can throw a NullPointerException. |
Check for null before invoking methods when null is possible. |
| Writing complex conditions without parentheses |
The intended grouping may be unclear. |
Use parentheses to make the logic easy to read. |
| Using relational operators with Boolean values |
Boolean values do not support numeric ordering comparisons. |
Use Boolean conditions and logical operators instead. |
20. Practical Program: Compare Two Numbers
This program demonstrates all six relational and equality operators using two integer values.
public class ComparisonOperatorsDemo {
public static void main(String[] args) {
int first = 15;
int second = 20;
System.out.println("first > second: " + (first > second));
System.out.println("first < second: " + (first < second));
System.out.println("first >= second: " + (first >= second));
System.out.println("first <= second: " + (first <= second));
System.out.println("first == second: " + (first == second));
System.out.println("first != second: " + (first != second));
}
}
Output:
first > second: false
first < second: true
first >= second: false
first <= second: true
first == second: false
first != second: true
Program Explanation
- The program declares two integer variables,
first and second.
- Each comparison operator checks a different relationship between the two values.
- Every comparison produces either
true or false.
- Parentheses make the comparison happen before the result is concatenated with the descriptive text.
- The
println() method displays each result.
21. Practical Program: Find the Largest of Three Numbers
Relational operators can be used to compare multiple values and determine which is largest.
public class LargestNumber {
public static void main(String[] args) {
int a = 45;
int b = 72;
int c = 60;
if (a >= b && a >= c) {
System.out.println("Largest number: " + a);
} else if (b >= a && b >= c) {
System.out.println("Largest number: " + b);
} else {
System.out.println("Largest number: " + c);
}
}
}
Output:
Largest number: 72
The program checks whether each candidate is greater than or equal to the other two values. Using >= also handles cases where two or more numbers share the largest value.
22. Practical Program: Validate a Marks Range
Relational operators can validate whether an input value is within a permitted range. The following example checks whether marks fall between 0 and 100, including both boundaries.
public class MarksValidation {
public static void main(String[] args) {
int marks = 85;
if (marks >= 0 && marks <= 100) {
System.out.println("Marks are valid.");
if (marks >= 40) {
System.out.println("Student has passed.");
} else {
System.out.println("Student has failed.");
}
} else {
System.out.println("Invalid marks. Enter a value from 0 to 100.");
}
}
}
Output:
Marks are valid.
Student has passed.
The outer condition checks the allowed range. The inner condition checks the passing threshold only after the marks have been validated.
23. Best Practices for Using Comparison Operators
- Use the correct operator: Distinguish between strict comparisons such as
> and inclusive comparisons such as >=.
- Use meaningful variable names: Names such as
minimumAge, passingMarks, and maximumBudget make comparisons easier to understand.
- Prefer readable conditions: Break complicated expressions into smaller Boolean variables or use parentheses.
- Compare String contents correctly: Use
equals() rather than == when checking whether two strings contain the same text.
- Handle possible null references: Validate references before calling methods on them.
- Be cautious with floating-point comparisons: Use an appropriate tolerance when working with approximate numerical results.
- Test boundary values: Check values immediately below, exactly at, and immediately above a threshold.
- Use logical operators appropriately: Combine multiple comparisons with
&& or || when a condition requires more than one test.
- Avoid unnecessary Boolean comparisons: Write
if (isAvailable) instead of if (isAvailable == true) when possible.
- Keep security checks server-side: Comparisons used for authentication, authorization, or payment validation must be part of a secure overall design.
24. Exercises for Practice
Beginner Exercises
- Declare two integers and print the results of
>, <, >=, and <=.
- Write a program to check whether two integers are equal using
==.
- Write a program that checks whether a number is not equal to zero.
- Compare a student's marks with a passing score using
>=.
- Check whether a product price is less than or equal to a specified budget.
Intermediate Exercises
- Find the largest of three numbers using relational operators.
- Validate whether a person's age falls within a specified inclusive range.
- Write a program to determine whether a number lies strictly between 10 and 100.
- Compare two strings using both
== and equals() and explain the results.
- Write a program that checks whether a score is valid and then assigns a grade.
Challenge Exercise: Employee Bonus Eligibility
Create a program that checks whether an employee qualifies for a bonus. The employee must have at least three years of service and a performance score of at least 80.
Requirements:
- Create variables for years of service and performance score.
- Use
>= to check both minimum requirements.
- Use
&& to combine the conditions.
- Display a suitable message for eligible and ineligible employees.
- Test the program with values exactly at the boundaries.
25. Interview Questions and Answers
Q1. What are relational operators in Java?
Answer: Relational operators compare numeric values and determine their ordering. The four common operators are >, <, >=, and <=.
Q2. What are equality operators in Java?
Answer: Equality operators check whether two values are equal or different. Java uses == for equality and != for inequality.
Q3. What is the difference between = and ==?
Answer: The = operator assigns a value to a variable. The == operator compares compatible values or, for object references, checks whether both references identify the same object.
Q4. What does the expression 10 >= 10 return?
Answer: It returns true because the greater than or equal to operator includes equality.
Q5. What is the difference between == and equals() for Strings?
Answer: For Strings, == checks reference identity, while equals() checks whether the character contents are equal.
Q6. Can relational operators compare Boolean values?
Answer: No. Operators such as > and < cannot be used to order Boolean values. Boolean values can be compared with == and !=, although direct Boolean conditions are usually clearer.
Q7. What is a Boolean expression?
Answer: A Boolean expression is an expression that evaluates to either true or false. For example, age >= 18 is a Boolean expression.
Q8. How can you check whether a number lies within a range?
Answer: Combine comparisons with the logical AND operator. For example, number >= 1 && number <= 100 checks whether a number is between 1 and 100, including both endpoints.
Q9. Why can comparing floating-point numbers with == be unreliable?
Answer: Floating-point types cannot represent every decimal fraction exactly. Arithmetic calculations can therefore produce small rounding differences. A suitable tolerance may be needed for approximate comparisons.
Q10. What is the result of 5 != 8?
Answer: The result is true because 5 and 8 are different values.
Q11. Can Java compare two object references with ==?
Answer: Yes. For compatible reference types, == checks whether both references point to the same object or both are null.
Q12. Why should boundary values be tested?
Answer: Boundary tests help identify mistakes involving inclusive and exclusive conditions. For a minimum score of 40, testing 39, 40, and 41 verifies behavior below, at, and above the threshold.
26. Quick Revision Checklist
> means greater than.
< means less than.
>= means greater than or equal to.
<= means less than or equal to.
== means equal to.
!= means not equal to.
- Comparison expressions produce Boolean results.
- Use
= for assignment and == for equality comparisons.
- Use
equals() to compare String contents.
- Use
&& to require multiple conditions to be true.
- Use
|| when at least one condition must be true.
- Use parentheses to make complex conditions clear.
- Be careful when comparing floating-point results.
- Test minimum, maximum, and boundary values.
27. Conclusion
Relational and equality operators form the foundation of decision-making in Java. Relational operators compare the size of numeric values, while equality operators determine whether values are equal or different. Their Boolean results make it possible to build conditional statements, validate input, compare scores, check limits, and implement business rules.
Understanding the distinction between assignment and equality, using the correct inclusive or exclusive operator, and comparing String contents with equals() will help you write clearer and more reliable Java programs.
Continue learning with the Core Java Training Course, explore more learning resources on the JustAcademy website, or register for a course demo.