class Base
{
public int i;
public Base(int a)
{
i=a;
}
}public class StringTest {
public static void changeStr(String str){
str="welcome";
}
public static void changeBase(Base b)
{
b.i=6;
}
public static void main(String[] args) {
String str="1234";
Base base= new Base(3);
changeBase(base);
System.out.println(base.i);
changeStr(str);
System.out.println(str);
}
} 我以为我明白了,可惜还是没明白
changeBase按“对象引用”的规则修改了i的值,
可是changeStr却没按“对象引用”规则,依然是“1234”
为什么呢?
{
public int i;
public Base(int a)
{
i=a;
}
}public class StringTest {
public static void changeStr(String str){
str="welcome";
}
public static void changeBase(Base b)
{
b.i=6;
}
public static void main(String[] args) {
String str="1234";
Base base= new Base(3);
changeBase(base);
System.out.println(base.i);
changeStr(str);
System.out.println(str);
}
} 我以为我明白了,可惜还是没明白
changeBase按“对象引用”的规则修改了i的值,
可是changeStr却没按“对象引用”规则,依然是“1234”
为什么呢?
一但生成一个String对象
你就永远无法改变它
JAVA里面不存在传地址,所以依然是“1234”
第二个传的是string string自然也不能直接改变
public static String changeStr(String str){
return "welcome";
}
public static void changeBase(Base b)
{
b.i=6;
}
public static void main(String[] args) {
String str="1234";
Base base= new Base(3);
changeBase(base);
System.out.println(base.i);
str = changeStr(str);
System.out.println(str);
} String是不变类,必须显示更改结果
第一个传的是对象b 对象b是不能改变的 //可是b变了
第二个传的是string string自然也不能直接改变 //这句是根据上一句推导出来的,所以这句也不成立
因为实际上传递的是引用的副本,所以的话,
Base base= new Base(3);
changeBase(base);
base引用只改变了对象的一个属性,并没有改变对象,
String str="1234";
changeStr(str);
str对象的副本已经被重写指向了“welcome”这个string对象,但是实际上str还是没有被修改,所以打印出来的还是1234,如果在changeStr(str)函数里增加一条打印语句估计会打印出welcome
-----------------------------------
class Base
{
public int i;
public Base(int a)
{
i=a;
}
}public class StringTest {
public static void changeBase(Base b)
{
b = new Base(7);
System.out.println("Inside: " + b.i);
}
public static void main(String[] args) {
Base base= new Base(3);
System.out.println("Before: " + base.i);
changeBase(base);
System.out.println("After: " + base.i);
}
}
-------------------------------------What's the output?
A:
Before: 3
Inside: 7
After: 7B:
Before: 3
Inside: 7
After: 3The actual answer here is B.Inside method "changeBase", Base reference variable b is initially points to the same Base instance (whose i is 3) as "base". Then it is reassigned with a new value, which points to a new Base instance (whose i is 7). The original Base reference variable "base' is not touched, nor does the original Base instance (whose i is 3).
System.out.println("After: " + base);