关于java:(string == null)和(string.length()== 0)之间的区别?

difference between (string == null) and (string.length() == 0)?

本问题已经有最佳答案,请猛点这里访问。

通过以下两种方式进行编程时,我得到了不同的仿真结果:

1
2
3
if (S == null) {
        return new LinkedList<>();
    }

1
2
int len = S.length();
if(len == 0) return new LinkedList<>();

第一个代码给了我["],它通过了测试。而第二个代码给了我[],但是失败了。
我还注意到还有另一种方法:S.isEmpty()

有人可以解释一下吗? 非常感谢!


String == null检查对象是否为null(什么都没有,甚至不是空字符串),String#length() == 0(实际上,您应该使用String#isEmpty()代替)检查字符串对象是否具有0个字符。另外,如果对象是null,则无法访问任何方法,它将抛出NullPointerException(或简称NPE)。


S是一个参考变量(您应该使用小写形式)。

S(或更确切地说,s)引用提供方法length()的对象。

如果s实际上是对对象的引用,则只能访问s引用的对象。如果s为null(s == null),则s不引用对象,因此,您不能调用方法length()。如果尝试,将收到NullPointerException。

当s引用一个对象时,可以在该对象上调用length方法。在这种情况下,它是一个字符串对象。字符串对象可能不包含任何字符(空字符串或"")。

  • String s; // just a reference, initial value is null
  • s =""; // s now references an empty string and is no longer null
  • new String(""); // create a new object with an empty string

在Java中,您永远不会真正使用对象。您只能使用对对象的引用,尽管在大多数情况下,看起来就像您直接使用该对象一样。

请记住,引用变量和对象实际上是不同的东西。


difference between (string == null) and (string.length() == 0)?

非常不一样。

当您检查(string == null)时,它将检查字符串引用是否指向任何现有对象。如果未引用任何对象,它将返回true

string.length() == 0仅检查现有String对象的内容,并查看其长度是否为0。如果在调用.length()时当前变量中不存在任何对象,则会得到NullPointerException


如果要传递给第二个字符串的字符串为null,则应发生异常,因为.length()在调用null字符串时将引发异常。


S == null表示,如果尝试打印某些内容,则不会有任何结果(或者可能是nullPointerEcxeption),因为null表示此变量内没有任何内容。

String.lenght(S) == 0表示您的字符串等于"

例如 :

1
2
3
4
5
6
7
8
9
10
11
12
13
14
String S1 = '';
String S2 = null;
try{
  System.out.println(S1.length() == 0) {
  System.out.println('S1 is not null');
}catch(nullPointerExeption e){
  System.out.println('S1 is null');
}
try{
  System.out.println(S2.length())//it will throw you a java.nullpointerexcption
  System.out.println('S2 is not null');
}catch(nullPointerExeption e){
  System.out.println('S2 is null');
}

系统会写

1
2
3
4
0
S1 is not null

S2 is null

如果String实例是null,则myInstance.length() == 0会抛出NullPointerException,因为调用未实例化实例的实例成员会使应用程序崩溃。

因此,如果不确定您的String实例是否已实例化,请始终执行null -check或更好的方法,对于Java 8或更高版本,请使用Optional来避免null's


创建新对象时,该对象的值最初为null
喜欢

1
String s=new String();

在这种情况下

1
s=null //but not s="";