Two String objects with same values not to be equal under the == operator. Explain How.
The == operator compares references and not contents. It compares two objects and if they are the same object in memory and present in the same memory location, the expression returns true else it returns false. It is quite possible that two same contents are located in different memory locations.
Following function will help to understand the concept public class Test
{
public static void main(String[] args)
{
String str1 = “abc”;
String str2 = str1;
String str5 = “abc”;
String str3 = new String(”abc”);
String str4 = new String(”abc”);
System.out.println(”== comparison - ” + (str1 == str2));
System.out.println(”equals method - ” + str1.equals(str2));
System.out.println(”== comparison - ” + str3 == str4);
System.out.println(”equals method - ” + str3.equals(str4));
System.out.println(”== comparison - ” + (str1 == str5));
}
}
//Output
== comparison - true
equals method - true
== comparison - false
equals method - true
== comparison - true