java中方法的参数传递的是什么?

来源:互联网 发布:python编程思想 编辑:程序博客网 时间:2024/06/06 19:41
public class Test1{
public static void main(String[] args){
String s = new String("hello");
System.out.println(s);
change(s);
System.out.println(s);
}
private void change(String str){
str = "world";
}
}

打印结果:

hello 

hello




要理解上面的问题,首先要理解对象和引用的关系。


Test1中,String s = new String("hello"); 在堆内存中保存了对象的值“hello”,而在栈内存中保存了对象的引用s,引用s保存了对象的地址123a。当调用change()方法传递参数时,实际上是拷贝了引用s所保存的地址123a,当然也就指向了同一个对象。



而当执行了str = "world"; 后,相当于str = new String("world"); 又创建了一个新的对象,这时候堆内存中就分配了一个新的地址用于存放新对象和他的值“world”。而栈内存中的str中保存的地址也变为新对象的地址123b,不再是123a,那么很显然str指向的是“world”这个对象。而引用s指向的对象的值还是“hello”。





public class Test2{
public static void main(String[] args){
int i = 4;
System.out.println(i);
change(i);
System.out.println(i);
}
private void change(int num){
num = 2;
}

}

打印结果:

4

4


再来看一下Test2,前面Test1讲的是引用数据类型,这里要讲基本数据类型。



基本数据类型的值是直接存储在栈内存的引用里的,当调用change()方法的时候,传递的实际上是引用i存放的值4。

当调用num = 2;时,实际上是在栈内存中新开辟了一个地址,值是2,并不影响原来的i。

public class Test2{
public static void main(String[] args){
int i = 4;
System.out.println(i);
change(i);
System.out.println(i);
}
private void change(int num){
num = 2;
}

}

打印结果:

4

4

0 0