Important Java Concept

How do you write the not equals sign on Java?

In this article, we will learn how do you write the not equals sign on Java.

 

Understanding != in Java

 

Now since we aim at understanding inequality, we need to first understand what equality is.

So, what if I ask you to prove
int a = 5;
int b = 5;
are equal.
 
Of course, you write the following code
public static void main(String[] args) {
int a = 5;
int b = 5;
System.out.println(a==b);
}
view raw not_equal.java hosted with ❤ by GitHub
 
OUTPUT:
  true

Very easy, right,

Now similarly, you can write a != b, now since a == b is true here, we know that a != b will be false.
Simply put, != checks if 2 things are not equal. In case a is not equal to b, you’ll get true else you’ll get false.

 

public static void main(String[] args) {
int a = 5;
int b = 5;
System.out.println(a!=b);
}
view raw not_equal2.java hosted with ❤ by GitHub
OUTPUT:

  false
However, this only works for primitive data types like int, float, double, etc.
For objects we need to use !.equals() to check if 2 objects are not equal to one another.

 

Understanding !.equals() in Java

 

Again we’ll  first understand .equals() to understand !.equals().


We know Strings are objects, so we can use .equals() with Strings as given below.

public static void main(String[] args) {
String a= "Java";
String b= "Python";
System.out.println(a.equals(b));
}
OUTPUT:

  false

Here, Java is not equal to Python, so a.equals(b) will be false. 

Let’s try !a.equals(b) now.

public static void main(String[] args) {
String a= "Java";
String b= "Python";
System.out.println(!a.equals(b));
}
OUTPUT:

  true

Here, Java is not equal to Python, so !a.equals(b) or simply put checking if a is not equal to b will be true. 

In this java tutorial, we learned how do you write the not equals sign on Java.
I hope this article helped you.

In case you have doubts, I suggest you take a live 1:1 lesson on this subject from me. I am an Oracle-certified tutor who would love to teach this stuff to you directly.
Aniket Malik

 

 

Do you want

Java Tutor?

Aniket Malik

Aniket Malik

ORACLE CERTIFIED JAVA TUTOR

🟢 Oracle Certified Java Expert

🟢 300 + ⭐ ⭐ ⭐ ⭐ ⭐

🟢 B.tech & M.tech in CSE

🟢 6+ Years of Teaching Experience

🟢 Worked as SE in Virtusa and Digidez

Do you want

Java Tutor?