今天做题遇到个问题。就是关于传值的问题。
看代码:
1、
public class File_55_80 {
 static void temp(StringBuffer t)
{
t.append(" Programe");

}
public static void main(String[] args) {
StringBuffer s=new StringBuffer("java");
temp(s);
System.out.println(s); }}
结果是:java programe.
书上说,可以改变引用变量的值,一切均是复制,这里stringbuffer t 是s的地址,按道理说是可以修改的,但是下面的代码我又看不懂了。
2、
public class File_55_80 {
 static void temp(String t)
{
t.replace('j','l');

}
public static void main(String[] args) {
String s=new String("java");
temp(s);
System.out.println(s); }}
为什么没有输出lava,而是java呢?

解决方案 »

  1.   

    String instance is immutable. Once it is created, it will not be changed.In your example 2, String instance s' reference is passed to method temp as parameter t. When t.replace('j', 'l') is invoked, a new String instance is created because t is immutable.You need to read books about String in Java.
      

  2.   

    String 类型是不可变的
    调用 temp方法中的t.replace( 'j ', 'l '); 是相当于产生了一个新的字符串,叫做lava ,而没有任何引用指向它,此
    所以当然不输出lava了
      

  3.   

    你后面一个问题牵涉到变量作用域的问题。你传递的只是java这个字符串的副本,或者说,你传递的是java这四个字母,所谓字面值,并没有直接把整个对象传递过去,这有点类似深复制和浅复制。你的确是创造了一个lava,只可惜的是,超出它周围的一对大括号,它就不能被访问了。而且,顺便说一句,你在改变一个String对象的内容的时候,你真正改变的并不是它的值,编译器创造了一个新的符合你要求的字符串,然后把这个String对象的指针指过去。
      

  4.   

    首先,查JDK文档,可以看到:
    StringBuffer类下append方法:
    public StringBuffer append(String str)
    Appends the specified string to this character sequence.(把指定的字符串追加到这个字符队列里)String类的replace方法:
    public String replace(char oldChar,char newChar)
    Returns a new string resulting from replacing all occurrences of oldChar in this string with newChar. (返回一个新的字符串结果 ....略...)显然,这2个方法执行后结果存放的位置不一样,append方法没产生新的对象,只是修改了原字符串的值;replace方法,新生成了个string 对象,并把方法的结果保存其中,而原字符串的值变了吗?没有!StringBuffer str=new StringBuffer("one ");
    String str2=str.append("two ").toString();
    System.out.println("str = "+str);
    System.out.println("str2= "+str2);

    String s=new String("one ");
    String s2=s.replace('e', 'X');
    System.out.println("s = "+s);
    System.out.println("s2= "+s2);