空字符串和空字符串的区别 [英] Difference between null and empty string
问题描述
空字符串 (String s = null
) 和空字符串 (String s = ""
) 有什么区别?
What is the difference between a null string (String s = null
) and an empty string (String s = ""
)?
这就是我所拥有的:
String s1 = ""; //print statement does not print any thing for s1 but s1.length()=0
String s2 = null;//print statement prints "null" for s2 but s2.length() gives exception
什么意思?
推荐答案
String s1 = "";
表示将空的 String
分配给 s1代码>.在这种情况下,
s1.length()
与 "".length()
相同,它将按预期产生 0
.
String s1 = "";
means that the empty String
is assigned to s1
.
In this case, s1.length()
is the same as "".length()
, which will yield 0
as expected.
String s2 = null;
表示将 (null
) 或根本没有值"分配给 s2
.所以这个,s2.length()
与 null.length()
相同,这将产生 NullPointerException
因为你不能在 Java 中调用 null
变量(指针,排序)的方法.
String s2 = null;
means that (null
) or "no value at all" is assigned to s2
. So this one, s2.length()
is the same as null.length()
, which will yield a NullPointerException
as you can't call methods on null
variables (pointers, sort of) in Java.
还有一点,声明
String s1;
其实效果一样:
String s1 = null;
然而
String s1 = "";
正如所说,是另一回事.
Is, as said, a different thing.
这篇关于空字符串和空字符串的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!