一、引用变量和值变量的区别
1.值类型的的数据都是存储在栈中。
2.引用类型,其变量的数据(其数据是一个地址值)存储在栈中,引用类型的真正数据储存在堆中。
3.八大基本数据类型-值类型,存放到栈中。其他的数据类型(String、数组、对象……)-引用类型,存放到堆中。
二、值类型和引用类型在方法的调用中
1.如果用值类型作为方法的实际参数传递,方法中将参数交换,并不影响本身的参数的改变。
1 public class Example01 {
2
3 public static void main(String[] args) {
4 int x=10;
5 int y=20;
6 System.out.println("x:"+x+" y:"+y);
7 exchange(x,y);
8 System.out.println("x:"+x+" y:"+y);
9
10 }
11 public static void exchange(int x,int y){
12 int tmp=x;
13 x=y;
14 y=tmp;
15 System.out.println("x:"+x+" y:"+y);
16 }
17 }
结果:
2.用引用类型作为实际参数传递,传递参数的本质还是传值,只是这个值是内存地址的引用而已。会影响本身参数改变。
public class Score {
int xx;
int yy;
}
1 public class Example01 {
2
3 public static void main(String[] args) {
4
5 Score score=new Score();
6 score.xx=10;
7 score.yy=20;
8 System.out.println("xx:"+score.xx+" yy:"+score.yy);
9 exchange(score);
10 System.out.println("xx:"+score.xx+" yy:"+score.yy);
11 }
12 public static void exchange(Score score){
13 int tmp=score.xx;
14 score.xx=score.yy;
15 score.yy=tmp;
16 System.out.println("xx:"+score.xx+" yy:"+score.yy);
17 }
18 }
结果:
图片解析:
3.典型思想错误示范
1 public class Example01 {
2
3 public static void main(String[] args) {
4
5 String x="I love you";
6 String y="I hate you";
7 System.out.println("x:"+x+" y:"+y);
8 exchange(x, y);
9 System.out.println("x:"+x+" y:"+y);
10
11 }
12 public static void exchange(String x,String y){
13 String tmp=x;
14 x=y;
15 y=tmp;
16 System.out.println("x:"+x+" y:"+y);
17 }
18 }
结果:
疑惑:为什么这里的明明是引用类型,但是却依然没有影响到主函数中的实参的值的改变呢?
解析:因为这里混淆了概念,实际上Java中所有的都是值传递,本代码中x,y中存储了地址值,在交换函数exchange()中,形参x,y交换了值,也就是交换了地址值。但是并没有交换真正的数据。
当函数执行完成,回到主函数中时,形参失效,而x,y中存储的地址值并没有交换,并且正真的数据值也没有交换,所以一切都没有改变。
注意:Java中所有的都是值传递
原文:https://www.cnblogs.com/Unlimited-Rain/p/12465357.html