Relational Operators in Java | About, Types and Examples

Relational Operators in Java | About, Types and Examples

5 mins readComment
Esha
Esha Gupta
Associate Senior Executive
Updated on Apr 4, 2024 17:30 IST

Have you ever wondered how Java programs make decisions? Relational operators like ==, !=, >, <, >=, and <= are key in Java for comparing values, enabling the code to make decisions and effectively control the flow based on these comparisons. They are essential for implementing logic in conditional statements and loops.Let's understand more!

 

 

Operators in Java are special symbols or keywords that are used to perform operations on variables and values. These operations can range from basic mathematical calculations to complex logical comparisons. Operators in Java are categorized into several types based on their functionality. In this blog, we will learn about one of its types in detail, which are relational operators!

Table of Content

 
Recommended online courses

Best-suited Java courses for you

Learn Java with these high-rated online courses

โ€“ / โ€“
350 hours
Free
6 months
โ€“ / โ€“
4 months
โ€“ / โ€“
โ€“ / โ€“
โ€“ / โ€“
1 month
โ‚น50 K
7 weeks
โ‚น7.8 K
3 months
โ‚น8.47 K
2 months
โ‚น7 K
6 months
โ‚น4 K
2 months

What is a Relational Operator in Java?

Relational operators in Java are used to establish a relationship between two operands. They compare the values and return a boolean result, either true or false. These operators are primarily used in conditions that control the flow of the program, such as in if statements, loops (for, while, do-while), and ternary operations. It's important to note that when comparing objects, relational operators compare references, not the content of the objects.

Types and Syntax of Relational Operators

Operator Type

Symbol

Syntax Example

Use Case

Notes

Equal to

==

a == b

Checks if two values are equal

Commonly used in conditional statements

Not Equal to

!=

a != b

Checks if two values are not equal

Useful for checking inequality

Greater than

>

a > b

Checks if the left operand is greater than the right operand

Determines if one value is larger than another

Less than

<

a < b

Checks if the left operand is less than the right operand

Useful for sorting and range checks

Greater than or equal to

>=

a >= b

Checks if the left operand is greater than or equal to the right operand

Often used in loops and conditionals

Less than or equal to

<=

a <= b

Checks if the left operand is less than or equal to the right operand

Common in conditional logic involving ranges or limits

Points to be Noted :

  • a and b are operands and can be literals, variables, or expressions.
  • These operators are commonly used with numeric data types (like int, float, double) but can also be used with characters (char).
  • In the case of object references, == and != check for reference equality, not the equality of the content.
  • Relational operators are crucial in control flow structures such as if statements, loops, and ternary operators for making decisions based on comparing values.

Java String Compare: A Guide to Effective String Comparison in Java
Java String Compare: A Guide to Effective String Comparison in Java
Have you ever wondered how to compare strings in Java? You can use various methods for that, like using equals(), using == Operator, using equalsIgnoreCase(), using compareTo() and using compareToIgnoreCase()....read more

What are Identifiers in Java?
What are Identifiers in Java?
Have you ever wondered how Java keeps everything organized and accessible? It's all because of identifiers. Those unique labels assigned to variables, methods, and classes. These crucial elements of Java...read more

Getting Started with Java Hello World Program
Getting Started with Java Hello World Program
Do you know the significance of the "Hello World" program in Java? It's the first step for many into the world of programming, serving as a simple yet profound introduction...read more

All About Assignment Operator in Java
All About Assignment Operator in Java
Have you ever wondered how assignment operators function in Java? They are special symbols used for assigning values to variables, with the most basic one being the equal sign (=)....read more

Mastering Bitwise Operator in Java
Mastering Bitwise Operator in Java
Have you ever wondered about the efficiency of low-level data manipulation in Java? Bitwise operators, like AND (&), OR (|), XOR (^), and shift operators (>, >>>), offer a powerful...read more

Examples Showing Usage of Relational Operators

Example 1: Age Verification for Eligibility

Problem Statement: Check if a person is eligible to vote based on their age.


 
public class AgeVerification {
public static void main(String[] args) {
int age = 20;
// Check if age is greater than or equal to 18
if (age >= 18) {
System.out.println("Eligible to vote.");
} else {
System.out.println("Not eligible to vote.");
}
}
}
Copy code

Output

Eligible to vote.

Example 2: Comparing Test Scores

Problem Statement: Determine if a student has scored higher than the passing score.


 
public class TestScoreComparison {
public static void main(String[] args) {
int studentScore = 75;
int passingScore = 60;
// Check if student score is greater than passing score
if (studentScore > passingScore) {
System.out.println("Student passed the test.");
} else {
System.out.println("Student failed the test.");
}
}
}
Copy code

Output

Student passed the test.

Example 3: Validating User Input Range

Problem Statement: Ensure a number entered by the user falls within a specific range.


 
public class InputRangeValidation {
public static void main(String[] args) {
int userInput = 35;
// Check if the input is within the range 1 to 100
if (userInput >= 1 && userInput <= 100) {
System.out.println("Valid input.");
} else {
System.out.println("Invalid input. Please enter a number between 1 and 100.");
}
}
}
Copy code

Output

Valid input.

Example 4: Checking Temperature for Freezing Point

Problem Statement: Determine if the water is in a solid state at a given temperature.


 
public class WaterStateCheck {
public static void main(String[] args) {
int temperature = -5; // Temperature in degrees Celsius
// Check if temperature is less than or equal to 0
if (temperature <= 0) {
System.out.println("Water is frozen.");
} else {
System.out.println("Water is not frozen.");
}
}
}
Copy code

Output

Water is frozen.

Example 5: Finding the Largest of Two Numbers

Problem Statement: Compare two numbers and find the larger one.


 
public class LargestNumber {
public static void main(String[] args) {
int number1 = 45;
int number2 = 30;
// Check which number is greater
if (number1 > number2) {
System.out.println("The larger number is: " + number1);
} else {
System.out.println("The larger number is: " + number2);
}
}
}
Copy code

Output

The larger number is: 45

Array Programs in Java | Beginner to Expert Level
Array Programs in Java | Beginner to Expert Level
Array programs in Java traverse from basic single-dimensional arrays to complex multi-dimensional arrays and dynamic arrays using ArrayList. From initializing and accessing array elements, to advanced operations like sorting and...read more

A Guide to Power Function in Java
A Guide to Power Function in Java
Have you ever wondered how mathematical power functions are implemented in programming languages like Java? In Java, the Math.pow() function is a powerful tool used to raise a number to...read more

Java Comments | About, Types and Examples
Java Comments | About, Types and Examples
Do you know what makes the code more readable? Comments, as they provide valuable context and explanations about the code, making it easier for both the original developers and others...read more

Let's Learn Logical Operators in Java
Let's Learn Logical Operators in Java
Have you ever wondered how logical operators in Java work? These operators, including AND (&&), OR (||), and NOT (!), are used to combine or invert boolean expressions, playing a...read more

All About Arithmetic Operators in Java
All About Arithmetic Operators in Java
Have you ever wondered how arithmetic operators in Java simplify mathematical calculations? Arithmetic operators in Java are simple yet powerful tools for performing numerical computations. Let's read more about it...read more

Conclusion

Thus, relational operators play a vital role in Java programming by enabling the comparison of values and making decisions based on these comparisons. They are simple yet powerful tools that are essential for implementing logic in various applications.

FAQs

What are Relational Operators in Java?

Relational operators in Java are used to compare two values and determine the relationship between them. They return a boolean result (true or false) based on the comparison.

What are the Types of Relational Operators in Java?

Java includes six relational operators:

  • == (equal to)
  • != (not equal to)
  • < (less than)
  • > (greater than)
  • <= (less than or equal to)
  • >= (greater than or equal to)

How are Relational Operators Used in Java?

Relational operators are used to compare two values or expressions. For example, a == b checks if a is equal to b, and x > y checks if x is greater than y.

What is the Difference Between == and equals() Method in Java?

== is a relational operator used to compare object references, while the equals() method is used to compare the content or value of objects. In most cases, when comparing objects for equality, it's recommended to use the equals() method.

Can Relational Operators Be Used with Non-Primitive Data Types?

Yes, relational operators can be used with non-primitive data types (objects) as long as those objects have implemented the equals() method. The equals() method defines how objects of a class are compared for equality.

About the Author
author-image
Esha Gupta
Associate Senior Executive

Hello, world! I'm Esha Gupta, your go-to Technical Content Developer focusing on Java, Data Structures and Algorithms, and Front End Development. Alongside these specialities, I have a zest for immersing myself in v... Read Full Bio