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.
int
is a primitive soa == c
=>true
a == b
=>true
b == c
=>true
With Strings the situation is slightly different.
String
s are effectively char arrays:char[]
but are not considered primitive types in Java.. so:"str1" == "str1"
=>false
since you're comparing two object references now.For this reason the
Object
class 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 theequals
method.In your example (above) you say:
This is incorrect.
ab
points to String that is "meowdeal" andabc
points 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.