值传递与引用传递

  • 值传递

方法在调用的时候,实际参数把它的值赋予给形式参数,但是形式参数的数据类型只能是基本数据类型和String。形式参数和实际参数在内存上是两个独立的变量,对形式参数的修改并不会影响实际参数的值。

public class ValuePassing {
    public static void main(String[] args) {
        int b = 10;
        testFunction(b); // 实际参数 传入参数不会改变参数本身的值
        System.out.println(b); 
    }
    
    public static void testFunction(int a){ //形式参数
        a=100;
    }
}
  • 引用传递

在方法调用时,传递的实际参数是java对象,也就是对象的内存空间的地址。而形式参数也会指向这一内存地址。注意被传递的形式参数的数据类型必须是引用数据类型

public class Student {
    int age;
}

public class ReferencePassing {
    public static void main(String[] args) {
        Student student = new Student();
        student.age = 28;
        testFunction(student);
        System.out.println(student.age);
    }

    public static void testFunction(Student student){
        student.age  = 18;
    }
}

具体描述如下:
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值