Difference between null and empty ("") Java String -
what difference between null
, ""
(empty string)?
i have written simple code this:
string = ""; string b = null; system.out.println(a==b); // false system.out.println(a.equals(b)); // false
and both statements return false
. seems, not able find actual difference between them.
"" actual string, albeit empty one.
null, however, means string variable points nothing.
a==b
returns false because "" , null not occupy same space in memory--in other words, variables don't point same objects.
a.equals(b)
returns false because "" not equal null, obviously.
the difference though since "" actual string, can still invoke methods or functions on like
a.length()
a.substring(0, 1)
and on.
if string equals null, b, java throw nullpointerexception
if tried invoking, say:
b.length()
if difference wondering == versus equals, it's this:
== compares references, if went
string = new string(""); string b = new string(""); system.out.println(a==b);
that output false because allocated 2 different objects, , , b point different objects.
however, a.equals(b)
in case return true, because equals
strings return true if , if argument string not null , represents same sequence of characters.
be warned, though, java have special case strings.
string = "abc"; string b = "abc"; system.out.println(a==b);
you think output false
, since should allocate 2 different strings. actually, java intern literal strings (ones initialized , b in our example). careful, because can give false positives on how == works.
Comments
Post a Comment