Saturday, May 2, 2026

Equality And Relational Operators in Java

In Java, the equality and relational operators are used to compare values and determine the relationship between operands. These operators determine whether one value is greater than, less than, equal to, or not equal to another.

The equality and relational operators generate a boolean result; true if the condition holds, and false if it does not. This makes Equality And Relational Operators in Java essential for decision‑making and control flow in programs.

List of Equality and Relational operators

Operator Description
==equal to
!=not equal to
>greater than
>=greater than or equal to
<less than
<=less than or equal to

Important Note- You must use "==" when testing two primitive values for equality. Do not confuse it with the assignment operator "=", which assigns a value to a variable.

Example:
int a = 5, b = 5;
System.out.println(a == b); // true
System.out.println(a = b);  // assigns b to a, doesn't compare

Refer post Difference between equals() method and equality operator == in Java to know when to use equals method and when to use == operator.

Java equality and relational operators example

Following example shows the Java equality and relational operators in action.

public class RelationalDemo {
  public static void main(String[] args) {
    int a = 7;
    int b = 5;
    int c = 7;
    
    // This should get printed
    if(a == c){
      System.out.println("Values of a and c are equal");
    }
        
    // This won't be printed
    if(a == b){
      System.out.println("Values of a and b are equal");
    }
    
    if(a != b){
      System.out.println("Values of and b are not equal");
    }
    
    if(a > b){
      System.out.println("a is greater than b");
    }
        
    if(a >= c){
      System.out.println("a is greater than or equal to c");
    }
    
    // This won't be printed
    if(a < b){
      System.out.println("a is less than b");
    }
    
    if(b < a){
      System.out.println("b is less than a");
    }
  }
}

Output

Values of a and c are equal
Values of and b are not equal
a is greater than b
a is greater than or equal to c
b is less than a

That's all for this topic Equality And Relational Operators in Java. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Java Basics Tutorial Page


Related Topics

  1. Arithmetic And Unary Operators in Java
  2. Conditional Operators in Java
  3. Array in Java
  4. String in Java Tutorial
  5. this Keyword in Java With Examples

You may also like-

  1. What are JVM, JRE and JDK in Java
  2. Java Automatic Numeric Type Promotion
  3. Why main Method static in Java
  4. Java Pass by Value or Pass by Reference
  5. Access Modifiers in Java - Public, Private, Protected and Default
  6. ArrayList in Java With Examples
  7. ConcurrentHashMap in Java With Examples
  8. Lambda Expressions in Java 8

No comments:

Post a Comment