String和StringBuffer作为参数传递(一个小注意事项)

 public static void main(String[] args) {
        String s1 = "Hello";
        String s2 = "World";
        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);//Hello-----------World
        changeBuffer(sb1, sb2);
        System.out.println(sb1 + "-------------" + sb2);//Hello-------------WorldWorld
    }

    private static void changeBuffer(StringBuffer sb1, StringBuffer sb2) {
        sb1 = sb2;
        sb2 = sb1.append(sb2);
    }

    private static void change(String s1, String s2) {
        s1 = s2;
        s2 = s1 + s2;
    }

  注意:StringBuffer直接赋值不会改变实际内容,如果做了操作就会改变

posted @ 2022-03-06 16:51  CGGirl  阅读(56)  评论(0)    收藏  举报