What is the difference between == and equals() in Java?
For primitives, == compares the values. For objects, == checks if both variables point to the same object. The equals() method checks if the content is the same (if the class overrides it, like String does).
public class Main {
public static void main(String[] args) {
String a = "java";
String b = "java";
String c = new String("java");
System.out.println(a == b); // same object in the string pool
System.out.println(a == c); // different objects
System.out.println(a.equals(c)); // same text
System.out.println(5 == 5);
}
}
Output
true
false
true
true
See Java Strings.
Learn more about the similar topics:
| Tutorials |
|---|
| No Content Found. |
| Exercises & Assignments |
|---|
| No Content Found. |
| Interview Questions & Answers |
|---|
| No Content Found. |