Difference between null and empty (“”) Java String

2018-12-31 23:41发布

What is the difference between null and the "" (empty string)?

I have written some simple code:

String a = "";
String b = null;

System.out.println(a == b); // false
System.out.println(a.equals(b)); // false

Both statements return false. It seems, I am not able to find what is the actual difference between them.

13条回答
流年柔荑漫光年
2楼-- · 2019-01-01 00:22
String s = "";
s.length();

String s = null;
s.length();

A reference to an empty string "" points to an object in the heap - so you can call methods on it.

But a reference pointing to null has no object to point in the heap and thus you'll get a NullPointerException.

查看更多
登录 后发表回答