1

下面是让我困惑的程序。下面程序的输出是

 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);
    }
}
4

1 回答 1

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 
于 2015-11-26T21:20:00.070 回答