package com;
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.println(ex.str+"and");
System.out.println(ex.ch);
}
public void change(String str2, char[] ch2) {
System.out.println("交换前:" + str2);
str2 = new String("test ok");
System.out.println("交换后:" + str2);
ch[0] = 'g';
}
}
输出结果为:
交换前:good
交换后:test ok
goodand
gbc
理由:因为String类是一个不可变类型,从声明那一刻起内存大小
是固定的不可改变的,如果改变它的值,jvm会重新开辟一块新的内存存储值,因此第一条输出语句中还是原值。