Java重温学习笔记,String、StringBuffer 和 StringBuilder的区别

String:字符串常量,字符串长度不可变。

StringBuffer:每次都会对 StringBuffer 对象本身进行操作,而不是生成新的对象,所以如果需要对字符串进行修改推荐使用 StringBuffer。它是线程安全的。

StringBuilder:此类在 Java 5 中被提出,它和 StringBuffer 之间的最大不同在于 StringBuilder 的方法不是线程安全的,但速度快。大多数场景下,推荐使用StringBiilder,除非考虑线程安全的问题。

关于String,看一段代码:

public class MyDemo {
   public static void main(String args[]){
        String s1 = "abc";            // 常量池
        String s2 = new String("abc");     // 堆内存中
        System.out.println(s1 == s2);        // false两个对象的地址值不一样。
        System.out.println(s1.equals(s2)); // true
        
        String s3 = "a"+"b"+"c";
        String s4 = "abc";
        System.out.println(s3 == s4); // true
        System.out.println(s3.equals(s4)); // true

        String s5 = "ab";
        String s6 = "abc";
        String s7 = s5 + "c"; // 先创建StringBuilder(或 StringBuffer)对象,通过append 连接得到"abc",再调用 toString() 转换得到的地址指向 s7
        System.out.println(s6 == s7);         // false
        System.out.println(s6.equals(s7));  // true
   }
}

另外,String 类中 concat() 方法和 + 号的区别在于,concat是通过复制数组再通过 char 数组进行拼接生成一个新的对象,地址值会有变动,而 ”+“号则不会。也就是说,上面代码中的"a"+"b"+"c"如果替换成"a".concat("b").concat("c"),那么s3不会等于s4。

原文地址:https://www.cnblogs.com/nayitian/p/14901010.html