JAVA String vs StringBuffer

时间:2013-07-12 11:04:04

标签: string object reference stringbuffer

以下是困扰我的程序。以下程序的输出是

 The USA 
main USA

如果我将所有String替换为StringBuffer,那么我得到了 "The USA main The USA"。请帮我理解这个。

 public class Confusing {
    public static void sss(String s1){
        s1= "The "+s1;
        System.out.println(s1);
    }

    public static void main(String args[]){
        String s1 = new String("USA");

        sss(s1);
        System.out.println("main "+s1);
    }
}

1 个答案:

答案 0 :(得分:0)

正确的方法就是这样:

public class Confusing {

  public static void sss(StringBuffer s1){
      StringBuffer the= new StringBuffer("the ");

      System.out.println(the.append(s1));
  }

  public static void main(String args[]){
      StringBuffer s1 = new StringBuffer("USA ");

      sss(s1);
      StringBuffer main = new StringBuffer("main ");
      System.out.println(main.append(s1));
 }
}

输出是:

the USA 
main USA