遇到这样一个问题,求高手解释下:
public class RefDemo0{
public static void main(String args[]){
String str1 = "hello" ; // 实例化字符串对象
System.out.println("fun()方法调用之前:" + str1) ;
fun(str1) ; // 调用fun()方法
System.out.println("fun()方法调用之后:" + str1) ;
}
public static void fun(String str2){ // 此处的方法由主方法直接调用
str2 = "world" ; // 修改字符串内容
}
};
输出结果为:
fun()方法调用之前:hello
fun()方法调用之后:hello
而
class Demo{
String temp = "hello" ; // 此处为了方便,属性暂时不封装
};
public class RefDemo0{
public static void main(String args[]){
Demo d1 = new Demo() ; // 实例化Demo对象
d1.temp = "world" ; // 修改temp属性的内容
System.out.println("fun()方法调用之前:" + d1.temp) ;
fun(d1) ;
System.out.println("fun()方法调用之后:" + d1.temp) ;
}
public static void fun(Demo d2){ // 此处的方法由主方法直接调用
d2.temp = "hey"; // 修改temp值
}
};
输出结果为:
fun()方法调用之前:world
fun()方法调用之后:hey
为什么两次输出结果会不同?
问题补充
String是静态的不能被修改,每次赋值都是改变引用。
而方法传值传的是指针
比如方法调用fun(str1);这样的,把str1的指针复制一下传入方法,而方法中改变了这个指针指向的对象。但是注意,原来的str1没有变。因为方法内部的str2是str1复制了一遍的。
而类的成员变量,改变了指向的对象。
值传递,引用传递 :P 好像是
这个问题高端了...
都不怕新手贴啊,这类问题在csdn老火了
[quote="freish"]都不怕新手贴啊,这类问题在csdn老火了[/quote]
很少上csdn,一直javaeye上混
[quote="jdonlkm"]原来是String类的内容不可改变,感谢李老师的热心指导[/quote]
楼主能详细说说吗?
这个问题太高深了,要追溯到JVM的堆栈分配了
同问,谁能详细解释一下!
第一个是值拷贝操作、第二个是对象引用的传递. 涉及到内存分配问题.
第一个程序中。str1指向“hello” 调用fun(str1)后 str2也指向"hello" ,并且在方法中创建一个“world”对象,然后让str2指向"world",这时,str1仍然指向"hello"。打印str1仍然是"hello".
第二个程序中。都是同一个引用temp改变指向的字符串对象。所以两次打印出来的结果会改变。
[quote="albeter"]第一个程序中。str1指向“hello” 调用fun(str1)后 str2也指向"hello" ,并且在方法中创建一个“world”对象,然后让str2指向"world",这时,str1仍然指向"hello"。打印str1仍然是"hello".
第二个程序中。都是同一个引用temp改变指向的字符串对象。所以两次打印出来的结果会改变。[/quote]
原来如此,哎,都没想到
换成stringbuffer结果也是一样,哈有StringBuilder也是一样!
public class RefDemo0 {
public static String fun(String str2) { // 此处的方法由主方法直接调用
str2 = "world"; // 修改字符串内容
return str2;
}
public static void main(String args[]) {
String str1 = "hello"; // 实例化字符串对象
System.out.println("fun()方法调用之前:" + str1);
str1 = fun(str1); // 调用fun()方法
System.out.println("fun()方法调用之后:" + str1);
}
}
你只是调用了而没有赋值! 不是么!?
第一个例子,从程序上直接分析就是fun方法传入参数str2,而str2既不是全局变量,fun方法有没有返回到哪里,所以str1的值都没有得到修改,str1和str2是两个不同的对象
从JVM内存上分析,下面是我画的JVM分析图,应该是比较明白的
可以参照 Java编程思想 附录A 有详细的说明