Java Not Equal

In Java, Not Equal Relational Operator is used to check if left operand is not equal to second operand. In this tutorial, we will learn how to use the Not Equal Operator in Java, with examples.

The symbols used for Not Equal operator is !=. Not Equal operator takes two operands: left operand and right operand as shown in the following.

</>
Copy
left_operand != right_operand

The syntax to check if x does not equal y using Not Equal Operator is

</>
Copy
x != y

The operator returns a boolean value of true if x is not equal to y, or false if not.

Since, Not Equal operator returns boolean value, we can use the above expression as a condition in Conditional Statements like If-Else.

Examples

In the following example, we take two integer values in x and y, and check if these two are not equal, using Not Equal Operator.

Main.java

</>
Copy
public class Main {
    public static void main(String[] args) {
        int x = 4;
        int y = 7;
        if (x != y) {
            System.out.println("x and y are not equal.");
        } else {
            System.out.println("x and y are equal.");
        }
    }
}

Output

x and y are not equal.

Since values in x and y are not equal, x != y returned true.

Now, let us take values in x and y such that they are equal, and check what Not Equal Operator returns for these values.

Main.java

</>
Copy
public class Main {
    public static void main(String[] args) {
        int x = 4;
        int y = 4;
        if (x != y) {
            System.out.println("x and y are not equal.");
        } else {
            System.out.println("x and y are equal.");
        }
    }
}

Output

x and y are equal.

Since values in x and y are equal, x != y returned false.

Conclusion

In this Java Tutorial, we learned what Not Equal Operator is, it’s syntax and how to use it in Java programs , with examples.