In Java, the "==" operator is used to compare references. When we use the == operator in Java it compares 2 objects, it checks whether the two objects refer to the same place in memory or not.
Example:
String str1 = new String("abc");
String str2 = new String("abc");
if(str1 == str2)
System.out.printlln("True");
else
System.out.println("False");
In the above example "==" operator will give false even though the both strings have the same value "abc"
Output:
False
The == operator compares the object location in memory means it checks whether the both string objects str1 and str2 refer to the same memory location or not, if yes then "==" returns true.
Example:
String str1 = new String("abc");
// here str2 and str1 reference the same place in memory
String str2 = str1;
if(str1 == str2)
System.out.printlln("True");
else
System.out.println("False");
In the above example both str1 and str2 reference the same memory place and the "==" compares the memory references for each object,therefore it will return true.
Output:
True
The equals() method
In Java, equals() method belongs to Object class. The equals() method is used to compare value of the two object not the memory location.
In Java, String class overrides the default equals() implementation in the Object class and it checks the values of the two strings only, not their locations in the memory.
Example:
String str1 = new String("abc");
String str2 = new String("abc");
if(str1.equals(str2))
System.out.printlln("String matched");
else
System.out.println("String not matched");
Output:
String matched
Hope this will help you :)
0 Comment(s)