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()
有人可以解释一下吗? 非常感谢!
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)?
非常不一样。
当您检查
如果要传递给第二个字符串的字符串为null,则应发生异常,因为
例如 :
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
喜欢
在这种情况下
1 | s=null //but not s=""; |