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 ");
System.out.print(ex.ch);
}
public void change(String str, char ch[]) {
str = "test ok";
ch[0] = 'g';
}
}
引用传递和值传递,集合传递的都是引用,非集合传递的是值
this.str修改的是类的实例变量,this代指此类,数组是引用类型,所以可以修改。string也是引用类型但是string是不可变的当你硬要修改str的值的时候虚拟机会分配一块内存给你的参数而不是你的变量。这种问题你要查阅一下引用类型的相关资料
对于change函数的两个形参str与ch:
String跟基本类型比如int类似,是值类型,修改形参str不会修改实参。
而char[]是引用,对其修改会作用到实参。