不多说,直接上干货!
//基本数据类型参数传递
class Demo
{
public static void main(String[] args)
{
int x = 3;
show(x);
System.out.println("x="+x);
}
public static void show(int x)
{
x = 4;
}
}
//引用数据类型参数传递
class Demo
{
int x = 3;
public static void main(String[] args)
{
Demo d = new Demo();
d.x = 9;
show(d);
System.out.println(d.x);
}
public static void show(Demo d)
{
d.x = 4;
}
}
一、对于基本数据类型参数传递代码的运行过程分析:
1、main方法进栈内存,main方法中有基本数据类型变量int x;
2、为main方法中的变量x赋值为3;
3、调用change(x)方法,则change方法进栈;
4、为change方法变量x赋值为4;
5、跳出change方法,同时change方法出栈,释放所有change方法和change方法中的x,即把x=4释放掉;
6、执行打印语句,些时的栈中只有main方法中的x,那么打印出的x=3;
7、跳出main方法,结束程序。
二、对于引用数据类型参数传递代码的运行过程分析:
1、main方法进栈内存,main方法中有一个类类型变量Demo d;
2、new创建Demo对象,在堆内存中开辟一个空间,并把空间地址传给d(我们这里假设为0x0078),并为该地址中的x初始化为0,然后把3赋给x;
3、把d所指堆内存(0x0078)中的x赋为9;
4、调用change(d)方法,change方法进栈,change方法中的对象d就是main方法中的d,指向之前的堆内存地址(0x0078);
5、把d所指堆内存(0x0078)中的x赋为4;
6、跳出change方法,同时change方法出栈,释放change方法和方法中的对象d;
7、执行打印语句,些时的栈中也是只有main方法,并且d指向堆内存(0x0078),该地址中的x就是步骤5中的值4;
8、跳出main方法,结束程序。
发表评论