search

Home  >  Q&A  >  body text

java - I don’t understand the code on line 13. Are sb and str not the same type?

public class TestStringBuffer{
    public static void main(String[] args){
        StringBuffer sb = new StringBuffer();
        sb.append("abc");
        sb.append("123");
        System.out.println("sb = " + sb); 
        sb.insert(3, "--"); 
        System.out.println("sb = " + sb); 
        sb.delete(2,6); 
        System.out.println("sb = " + sb);
        sb.reverse();
        System.out.println("sb = " + sb); 
        String str = sb.toString();  // 13行
        System.out.printf("str = " + str);
    }
}
漂亮男人漂亮男人2775 days ago382

reply all(2)I'll reply

  • 阿神

    阿神2017-05-17 10:06:19

    StringBuffer 
    String

    How can this be the same type?StringBuffer在做字符串连接 + 或者输出的时候
    会隐式执行toString()转化为String

    Line 13 is the displayed execution sb.toString()sb转换为 String

    reply
    0
  • 天蓬老师

    天蓬老师2017-05-17 10:06:19

    StringBuffer: String buffer
    String: String
    When modifying a string, you need to use the StringBuffer and StringBuilder classes.
    Different from the String class, objects of the StringBuffer and StringBuilder classes can be modified multiple times without generating new unused objects .

    The StringBuilder class was proposed in Java 5. The biggest difference between it and StringBuffer is that the methods of StringBuilder are not thread-safe (cannot be accessed synchronously).

    Since StringBuilder has a speed advantage compared to StringBuffer, it is recommended to use the StringBuilder class in most cases. However, in cases where the application requires thread safety, the StringBuffer class must be used.

    reply
    0
  • Cancelreply