Learn the difference between == and ===: Java vs JavaScript Explained. Understand reference comparison, value comparison, and examples
== operator :-
public class OperatorTest {
public static void main(String[] args) {
String s1 = new String("welcome");
String s2 = new String("welcome");
String s3 = "hello";
String s4 = "hello";
// Using == operator
System.out.println(
"Check operator with new object reference: " + (s1 == s2));
System.out.println(
"Check operator with string pool reference: " + (s3 == s4));
}
}
Output :
Check operator with new object reference: false
Check operator with string pool reference: true
=== operator :-
- Java does not support the === The === operator is available in JavaScript.
- The === operator is used in JavaScript to compare both value and data type.
- The strict equality (===) operator compares both the value and the data type of two variables.
In the below example a is a Number and b is a String. Since their data types are different, the === operator returns false.
var a = 20; // Number
var b = '30'; // String
console.log(a === b);
Output :
false
How == Works with Primitive Data Types
For primitive data types such as int, char, float, and boolean, the == operator compares the actual values stored in the variables. If both values are equal, it returns true; otherwise, it returns false.
public class PrimitiveComparison {
public static void main(String[] args) {
int a = 10;
int b = 10;
System.out.println(a == b);
}
}
Output :
true