Tuesday, 6 June 2017

Equality and Relational Operators in Java

The equality and relational operators evaluate the relationship between the values of the operands. These operators determine if one operand is greater than, less than, equal to, or not equal to another operand.

The equality and relational operators generate a boolean result. If the relationship is true then the result is true if relationship is untrue the result is false.

Equality and Relational operators description

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

Note that you must use "==" when testing two primitive values for equality, not "=" which is assignment operator.

Example code

public class RealationalDemo {

    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!


Related Topics

  1. Arithmetic and Unary Operators in Java
  2. Conditional Operators in Java
  3. Ternary operator in Java
  4. instanceof Operator in Java
  5. BigDecimal in Java

You may also like -

>>>Go to Java Basics page

No comments:

Post a Comment