Day4Java为什么是值传递

来了来了,完坑了
我们来看看这两个代码,

package com.cskaoyan.object.syntax.methodarg;

/**
 * @version 1.0
 */
class Demo2 {
  int a;
}

public class TestQuote2 {

  public static void main(String args[]) {
    Demo2 d1 = new Demo2();
    d1.a = 1;

    Demo2 d2 = new Demo2();
    d2.a = 2;

    System.out.println(d1.a); //1
    System.out.println(d2.a);// 2
    function(d1, d2);
    System.out.println(d1.a);
    System.out.println(d2.a);
  }

  private static void function(Demo2 d1, Demo2 d2) {
    Demo2 temp;
    temp = d1;
    d1 = d2;
    d2 = temp;
    //System.out.println("function: " + "d1.a = " + d1.a + ", d2.a = " + d2.a);
  }
}


package com.cskaoyan.object.syntax.methodarg;

/**
 * @version 1.0
 */

class Demo1 {
  int a;
}

public class TestQuote1 {

  public static void main(String args[]) {
    Demo1 d1 = new Demo1();
    d1.a = 1;

    Demo1 d2 = new Demo1();
    d2.a = 2;

    System.out.println(d1.a);
    System.out.println(d2.a);
    function(d1, d2);
    System.out.println(d1.a);
    System.out.println(d2.a);
  }

  // 方法的参数类型,都是引用类型
  private static void function(Demo1 d1, Demo1 d2) {
    //交换 d1 和 d2这两个引用变量所指向的对象的 成员变量a的值
    int tmp; //局部变量
    tmp = d1.a;
    d1.a = d2.a;
    d2.a = tmp;
  }
}

你猜出来这两个的正确输出值吗

我们来看看在内存的存储情况
在这里插入图片描述
在这里插入图片描述
行了。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值