Java中null和""的疑问

public class ArrToStr {
	static String str ;
	static String str1 = "";
	static String str2 = "";	
	public static void main(String[] args){
		System.out.println(str==str1);
		System.out.println(str instanceof Object);
		System.out.println(str1 instanceof Object);
		
		System.out.println(str);
		System.out.println("null".equals(str));
		System.out.println(str==null);
		
		System.out.println(str1.length());
		System.out.println(str1==str2);
	
		String str3 = "abc";
		String str4 = str3;
		String str5 = new String("abc");
		String str6 = new String("abc");
			    
	    System.out.println(str3==str4);
		System.out.println(str5==str6);
		System.out.println(str + str3);
	}
}
通过上述测试代码分析:
  • 比较null和""的不同
  1. String str = null是指str这个变量指向空对象;而“”是一个包含空字符的字符串对象。
  2. str == str1返回false,因为“”和null不在同一内存地址空间,也就是说,着两个变量没有指向同一对象。
  3. "null".equals(str)返回false。因为空串的值不是“null”。
  4. 空串str1是可以调用String对象的方法的,比如str1.length()的值为0;而str.length()将会抛出异常NullPointerException。
  • 比较==和equals的不同
  1. str3==str4返回true,因为着两个变量指向同一个对象"abc"(即内存中同一地址空间);而str==str6返回false,因为用new在开辟了两个不同的空间来存储两个“abc”对象,这样着两个变量所指向的地址就不同。
  2. equals指的是当字符串不为空,并且字符串的值一样时就返回true。
  • 为什么str打印出来是“null”?
我们查看PrintStream的源码,其实Java在println的时候进行了处理:
public void print(String s) {
        if (s == null) {
            s = "null";
        }
        write(s);
    }

  • 为什么str+str3打印出来是“nullabc”?
String的相加实际是被处理成StringBuilder的append方法。好,再看StringBuilder的源码,发现调用的是父类的方法:
 public StringBuilder append(String str) {
        super.append(str);
        return this;
    }
   public AbstractStringBuilder append(String str) {
        if (str == null) str = "null";
        int len = str.length();
        ensureCapacityInternal(count + len);
        str.getChars(0, len, value, count);
        count += len;
        return this;
    }

java运行过程中特殊的疑问一定不要轻易放过,查看源码会找到答案。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值