面试题:关于StringBuffer()源码的深度理解Debug分析

import org.junit.Test;

/**
 * @author CH
 * @create 2021 上午 11:23
 */
public class IDEADebug {

    @Test
    public void testStringBuffer(){
        String str = null;
        StringBuffer sb = new StringBuffer();
        sb.append(str);//把null当4个字母添加进去

        System.out.println(sb.length());//4

        System.out.println(sb);//"null"

        StringBuffer sb1 = new StringBuffer(str);//抛异常NullPointerException空指针异常
        System.out.println(sb1);//

    }
}

 问题:

为什么 sb.append(str)后的str.length是4?

 

 进入StringBuffer()方法:

下一行:

 进入super.append(str);

进入return appendNull();

 

 

 进入StringBuffer()

 

.length所以是空指针异常

附录:

/**
* Constructs a string buffer with no characters in it and
* the specified initial capacity.
*
* @param capacity the initial capacity.
* @exception NegativeArraySizeException if the {@code capacity}
* argument is less than {@code 0}.
*/
public StringBuffer(int capacity) {
super(capacity);
}

/**
* Constructs a string buffer initialized to the contents of the
* specified string. The initial capacity of the string buffer is
* {@code 16} plus the length of the string argument.
*
* @param str the initial contents of the buffer.
*/
public StringBuffer(String str) {
super(str.length() + 16);
append(str);
}

StringBuffer类 
StringBuffer 类不同于String ,其对象必须使用构造器生成。有 三 个 构造 器 :
StringBuffer() :初始为 容量为16 的字符串缓冲区
StringBuffer(int size) :构造 指定容量的字符串缓冲区
StringBuffer(String str) :将内容初始化为指定字符串内容

   

StringBuffer 类的常用方法
StringBuffer append(xxx):提供了很多的append()方法,用于进行字符串拼接
StringBuffer delete(int start,int end):删除指定位置的内容
StringBuffer replace(int start, int end, String str):把[start,end)位置替换为str
StringBuffer insert(int offset, xxx):在指定位置插入xxx
StringBuffer reverse() :把当前字符序列逆转

不积跬步,无以至千里;不积小流,无以成江海。
原文地址:https://www.cnblogs.com/CCTVCHCH/p/14668851.html