本帖最后由 潜王伟 于 2011-11-18 14:07 编辑
null表示没有引用任何对象,是真正的空值。
""是声明了一个对象实例,是空字符串
你可以用这个程序测试一下,就知道了:
public class TestNull {
static String s;
public static void main(String args[]) {
String s1 = null ;
String s2 = "" ;
String s3 = new String( "" );
System.out.println( " s: " + s);
System.out.println( " s1: " + s1);
System.out.println( " s2: " + s2);
System.out.println( " s1==s: " + (s1 == s));
System.out.println( " s1==s2: " + (s1 == s2));
System.out.println( " s2==\ " \ " : " + (s2 == "" ));
System.out.println( " s3==s2: " + (s2 == s3));
System.out.println( " s2.equals(s1): " + s2.equals(s1));
System.out.println( " s2.equals(s3): " + s2.equals(s3));
System.out.println(s1.equals(s2)); // throw java.lang.NullPointerException
}
}
结果:
s:null
s1:null
s2:
s1==s:true
s1==s2:false
s2=="":true
s3==s2:false
s2.equals(s1):false
s2.equals(s3):true
Exception in thread "main" java.lang.NullPointerException
at TestNull.main(TestNull.java:17)
说明""是一个堆中值,堆空间有分配...
而null,例如代码中的这句: String s1 = null ; 这句话在栈内是分配了空间的,但在堆内是没有分配的
如有错误,敬请指正! |