public class Example{
String str=new String("good");
char[]ch={'a','b','c'};
public static void main(String args[]){
Example ex=new Example();
ex.change(ex.str,ex.ch);
System.out.print(ex.str+" and ");
Sytem.out.print(ex.ch);
}
public void change(String str,char ch[]){
str="test ok";
ch[0]='g';
}
}
结果是多少
String str=new String("good");
char[]ch={'a','b','c'};
public static void main(String args[]){
Example ex=new Example();
ex.change(ex.str,ex.ch);
System.out.print(ex.str+" and ");
Sytem.out.print(ex.ch);
}
public void change(String str,char ch[]){
str="test ok";
ch[0]='g';
}
}
结果是多少
public void change(String str,char ch[],int i){
str="test ok";
ch[0]='g';
i++;
}
}public class Test8 {
public static void main(String args[]){
String str="good";
char ch[]={'a','b','c'};
int i=3;
Change cha=new Change();
cha.change(str,ch,i);
System.out.println(str);
System.out.println(ch);
System.out.println(i);
}
}结果为:
good
gbc
3
可见数组和其它类型不一样,传的是地址,结果改变
全局变量仍然还是"good"LZ最后打印的是全局变量str
所以是"good and gbc"
/**
* @author nuskwill
* @date 2008-9-19
*/
public class Example{
String str=new String("good");
char[]ch={'a','b','c'};
int i=1;
String tem[]={"11","22","33"};
F f = new F(10,"test");
public static void main(String args[]){
Example ex=new Example();
ex.change(ex.str,ex.ch,ex.i,ex.tem,ex.f);
System.out.println(ex.str);
System.out.println(ex.ch);
System.out.println(ex.i);
System.out.println(ex.tem[0]+" "+ex.tem[1]);
System.out.println(ex.f.kk+" "+ex.f.ss);
}
public void change(String str,char ch[],int i,String tem[],F f){
str="test ok";
ch[0]='g';
i++;
tem[0]="111";
f.kk=100;
}
} class F{
int kk;
String ss;
F(int k,String s){
kk=k;
ss=s;
}
}
结果为:
good
gbc
1
111 22
100 test说明非基础数据类型(也非string)传递的是 地址.
good and gbc
去我博客看下,对这类的介绍很详细。
static String str="ggggggg";
static int i = 1;
static char ch[]={'a','b','c'};
public static void main(String[] args) {
Variable2 cha=new Variable2();
cha.change(str,ch,i);
System.out.println(str);
System.out.println(ch);
System.out.println(i);
}
void change(String str,char ch[],int i){
str = "hello ok";
ch[0] = 'k';
i = 100;
}
}
Char[] 传的是地址,改变值就等于改变了内存中原先的数组的值。
故答案为: good and gbc
每次重新赋值引用地址都会改变,原来的地址就放入垃圾回收....
我想这个原因,估计是编码问题。