Is c point to a or is c point to the same memory that a is pointing to?
Why does the following code print "We are equal"?
Thanks in advance
public static void main(String args[]) {
String a = "10";
String b = "10";
String c = a;
if(c.equals(b)) {
System.out.println("We are equal ");
}
else {
System.out.println("Not equal! ");
}
}
Java stores objects by reference... the reference just happens to be the value when we use primitives.
intis a primitive soa == c=>truea == b=>trueb == c=>trueWith Strings the situation is slightly different.
Strings are effectively char arrays:char[]but are not considered primitive types in Java.. so:"str1" == "str1"=>falsesince you're comparing two object references now.For this reason the
Objectclass has theequals()method which allows you to compare reference objects (non-primitives) via something other than the object reference ID. TheString(a subclass of Object.class) class overrides theequalsmethod.In your example (above) you say:
This is incorrect.
abpoints to String that is "meowdeal" andabcpoints to a String that is also "meowdeal"... but crucially they are two distinct instances. Therefore:ab==abc=>false- here your checking for reference equality - are they the same object reference (no they are not)ab.equals(abc)=>true- here you're checking for string equality (isab's"meowdeal"the same asabc's"meowdeal"- yes it is.This is one of those curveball interview questions you might get from time to time so worth being aware of.