What is ==?
- The operator is used reference comparison.
- It compares whether two variables refer to the same object in memory.
Example:
String s1 = new String("Java");
String s2 = new String("Java");
System.out.println(s1 == s2);
Output:
false
Here, s1 and s2 contain the same text, but they are stored in different memory locations. Therefore, == returns false.
What is equals()?
- The equals() method compares the actual content or values of two objects.
Example:
String s1 = new String("Java");
String s2 = new String("Java");
System.out.println(s1.equals(s2));
Output:
true
The content of both strings is "Java", so equals() returns true.
Top comments (0)