public class Example {
String str = new String("good");
char[] ch = { 'a', 'b', 'c' };
int a=3;
public static void main(String args[]) {
Example ex = new Example();
ex.change(ex.str, ex.ch,ex.a);
System.out.print(ex.str + " and ");
System.out.print(ex.ch);
System.out.print(ex.a); } public void change(String str, char[] ch,int a) {
str = "te";
ch[0]='g';
a=5;
}
}
运行结果是 good and gbc 3 为什么String 和int的值都没有变 而字符组改变了呢 谁能帮忙讲解一下
String str = new String("good");
char[] ch = { 'a', 'b', 'c' };
int a=3;
public static void main(String args[]) {
Example ex = new Example();
ex.change(ex.str, ex.ch,ex.a);
System.out.print(ex.str + " and ");
System.out.print(ex.ch);
System.out.print(ex.a); } public void change(String str, char[] ch,int a) {
str = "te";
ch[0]='g';
a=5;
}
}
运行结果是 good and gbc 3 为什么String 和int的值都没有变 而字符组改变了呢 谁能帮忙讲解一下
public class Example {
String str1 = new String("good");
char[] ch = { 'a', 'b', 'c' };
int a=3;
public static void main(String args[]) {
Example ex = new Example();
ex.change(ex.str1, ex.ch,ex.a);
System.out.println("str:"+ex.str1);
System.out.println("ch:"+ex.ch[0]);
System.out.println("a:"+ex.a);
System.out.println(""); } public void change(String str, char[] ch,int a) {
str = "te";
//ch[0]='g';
for(int i =0;i<ch.length;i++){
System.out.print(ch[i]);
System.out.println("");
}
// System.out.print("jllll:"+ch[0]); a=5;
}
}因为他是一个数组,你得告诉他要输出数组中的那一个才行!
楼主可以看一下函数调用时参数传递的两种方式,以及变量的作用范围。在你的change函数中String str, int a都是局部变量,不会对主程序中的值产生影响
而char[] ch实际传递的是这个数组的地址,你的change函数和主程序访问的ch是同一块内存,所以修改后会产生相互影响
字符数组对象储存在堆中,还在栈中定义一个特殊的变量,让栈中这个变量的取值等于数组或对象在堆内存中的首地址,栈中的这个变量就成了数组或对象的引用变量。你通过栈中的这个变量修改了堆中储存的数组值,当你退出这个方法作用域范围时,栈中的这个引用变量释放。你堆中作的修改没变。而你全局的那个数组引用变量还没释放,通过全局的那个引用变量,你打印的是堆中的那个数组值。
也算是月经帖了。推荐你看一下这个帖子,大致就明白了,懒得给你打字了。http://topic.csdn.net/u/20100610/12/e2e7f92f-e16a-401e-bca9-698db71a280c.html
String和int是在change方法里的局部变量放在stack(栈)里,而字符数组是存在heap堆内存里面,在main方法执行new的时候,在堆内存里有一块是ex对象的(值分别是"good"、abc、3),在执行change的时候,在这里操作change了,主要看这个这个传值的过程,首先会在stack内存分别放三个小块存传好就是(a=5,str=te,ch(0)=g),他们位于栈内存,在方法调用完后java来及回收机制自动回收,a和str没有指向并改变堆内存中的a和str,所以它们没有改变,而其中的ch(0)=g,会指向堆内存ch,使ch=gbc执行完后,stack内存的三个小块存(a=5,str=te,ch(0)=g)消失,最后的内存就是stack里的ex指向heap里的(a=3,str="good",ch={'g','b','c'})
LZ可以把内存图画出来就清楚了。
LZ懂了就给分哈,嘿嘿,打字手都酸了