[Interview] Pass-by-value vs. Pass-by Reference

本文深入探讨了Java中值传递和引用传递的区别,并通过实例详细解释了如何在Java中正确地处理对象和基本类型的参数传递。文章还展示了如何改变对象属性以及数组内容的变化。

Java is pass-by-value.

Pass by value: make a copy in memory of the actual parameter's value that is passed in.

Pass by reference: pass a copy of the address of the actual parameter.

This code will not swap anything:

void swap(Type a1, Type a2) {
    Type temp = a1;
    a1 = a2;
    a2 = temp;
}

For this code, since the original and copied reference refer the same object, the member value gets changed:

class Apple {
    public String color = "red";
}
public class main {
    public static void main(String[] args) {
        Apple a1 = new Apple();
        System.out.println(a1.color); //print "red"
        changeColor(a1);
        System.out.println(a1.color); //print "green"
    }
    public static void changeColor(Apple apple) {
        apple.color = "green";
    }
}

Java does manipulate objects by reference, and all object variables are references. However, Java doesn't pass method arguments by reference; it passes them by value.

Some more examples

public class Main {
    public static void main(String[] args) {
        Student s = new Student("John");
        changeName(s);
        System.out.printf(s); // will print "John"
        modifyName(s);
        System.out.printf(s); // will print "Dave"
    }
    public static void changeName(Student a) {
        Student b = new Student("Mary");
        a = b;
    }
    public static void modifyName(Student c) {
        c.setAttribute("Dave");
    }
}
public static void changeContent(int[] arr) {
   // If we change the content of arr.
   arr[0] = 10;  // Will change the content of array in main()
}

public static void changeRef(int[] arr) {
   
   arr = new int[2];  // If we change the reference
   arr[0] = 15; // Will not change the array in main()
}

public static void main(String[] args) {
    int [] arr = new int[2];
    arr[0] = 4;
    arr[1] = 5;
    changeContent(arr);
    System.out.println(arr[0]);  // Will print 10..
    changeRef(arr);
    System.out.println(arr[0]);  // Will still print 10.. 
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值