Java == operator
Java == Operator
The Java == operator compares two values or object references for equality. The == operator compares references and not values.
== Operator
When comparing primitive data types (int, char, double, etc.), the == operator checks if the values are identical.
When comparing objects (instances of classes), the == operator checks if the two references point to the same object in memory.
Example
The following demonstrates == operator:
package com.testingdocs.stringmethods;
public class ExampleProgram {
public static void main(String[] args) {
String str1 = "TestingDocs";
String str2 = "TestingDocs";
String str3 = new String("TestingDocs");
System.out.println(str1==str2); // should be true
System.out.println(str1==str3); // should be false
}
}
Program Output
The program produces the following output:
true
false
The str1 and str2 refer to the same string in the String pool.
The str1 and str3 return false because they refer to different locations. The str1 refers to the String pool and str3 refers to the heap memory location.
For object equality based on value (e.g., checking if two objects represent the same logical entity), you should override the equals method in your class and use it instead of ==. The equals method is intended to compare the contents of objects for logical equality.
You can use the == operator to compare primitives or check if two references point to the same object, and use equals() method for comparing the content of objects.
Java Tutorials
Java Tutorial on this website:
For more information on Java, visit the official website :