zoukankan      html  css  js  c++  java
  • Java中未被初始化的字符串打印出“null”的问题的分析

    今天在研究Java面试题的时候发现了这道题,觉得挺有意思,记录下来。 一个为null的字符串被println出来会是什么呢。

    public static void main(String[] args) {
    
    
    String s = null;
    
    
    System.out.println(s+"aaaa");
    
    }
    

    输出是“nullaaaa” 这是为什么呢,String未被初始化是不可能成为“null”的,因为它是null的。 翻看了一下PrintStream,发现在他打印的时候做了马脚,源码是这样子的

     public void print(String s) {
     if (s == null) {
     s ="null";
    }
    write(s);
    }
    

    还有一个附加的问题是如果打印s+s会发生什么情况,两个null变量相加被打印,首先执行的是相加,查看反编译的Java代码知道是执行了StringBuilder的append方法,我们查看源码

     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;
    }
    

    发现一样对null的字符串进行了特殊的处理。

  • 相关阅读:
    PHP的错误和异常处理
    PHP 页面编码声明方法详解(header或meta)
    Sentinel实现Redis高可用
    Linux学习系列之Iptables
    Python学习系列之logging模块
    [scrapy]Item Loders
    [scrapy]实例:爬取jobbole页面
    mongo开启验证
    python创建虚拟环境
    elastalert邮件报警
  • 原文地址:https://www.cnblogs.com/liubey/p/8695954.html
Copyright © 2011-2022 走看看