Java-23.2 String,StringBuffer,StringBuilder的区别

1、String,StringBuffer,StringBuilder的区别
  1、String的内容不可变,而StringBuffer和StringBuilder的内容是可变的
  2、StringBuffer是同步线程安全的,数据安全,效率低
     StringBuilder是不同步的,线程不安全,数据不安全,效率高

2、StringBuffer和数组的区别:

  1、它们两个都可以被看作是一个容器,装一些数据

  2、但是StringBuffer里面的数据都是字符串数据,数组可以存放不同数据类型的数据,但是同一个数组只允许存放同一类型的数据

3、String类和StingBuffer类当做参数传递时的区别:

/*
        看程序写结果:
            String作为参数传递
                传递的是值,对外面本身变量的值没有任何影响。
            StringBuffer作为参数传递
                只有当谁有操作的时候,那个StringBuffer才会变化,因为方法消失前对缓冲池进行了操作
 */

public class StringBufferText5 {
    public static void main(String[] args) {
        String s1 = "hello";
        String s2 = "world";
        System.out.println(s1==s2);//false
        System.out.println(s1 + "--" + s2); //hello--world
        change(s1, s2);
        System.out.println(s1 + "--" + s2); //hello--world

        StringBuffer sb1 = new StringBuffer("hello");
        StringBuffer sb2 = new StringBuffer("world");
        System.out.println(sb1==sb2);//false
        System.out.println(sb1+"---"+sb2); //hello--world
        change2(sb1,sb2);
        System.out.println(sb1+"---"+sb2); //hello--worldworld

    }

    public static void change2(StringBuffer sb1,StringBuffer sb2){
        sb1 = sb2;
        sb2.append(sb1);
        System.out.println(sb1==sb2);//true
        System.out.println(sb1+"***"+sb2);//worldworld***worldworld

    }

    public static void change(String s1, String s2) {
        s1 = s2;
        s2 = s1 + s2;
        System.out.println(s1+"---"+s2);//world--worldworld
    }
}

 

posted @ 2021-10-10 20:41  艺术派大星  阅读(37)  评论(0)    收藏  举报
levels of contents