值传递还是引用传递

public class QQ {

    public static void main(String[] args) throws ParseException {
        int val = 5;
        changeVal(5);
        System.out.println(val);

        // Integer is a final class
        changeVal(Integer.valueOf(val));
        System.out.println(val);

        String valStr = "good";
        // String is a final class
        changeVal(valStr);
        System.out.println(valStr);

        QQ.Color color = new QQ.Color();
        color.setId(5);
        changeVal(color);
        System.out.println(color.getId());

    }

    public static void changeVal(int val) {
        val = 1;
    }

    public static void changeVal(Integer val) {
        val = Integer.valueOf(1);
    }

    public static void changeVal(String val) {
        val = "bad";
    }

    public static void changeVal(QQ.Color color) {
        color.setId(1);
    }

    static class Color {
        private int id;

        public int getId() {
            return id;
        }

        public void setId(int id) {
            this.id = id;
        }
    }
}

# 输出结果为:

5
5
good
1

其实java中方法参数传递方式都是按值传递。
如果参数是基本类型,传递的是基本类型的字面量值的拷贝。
如果参数是引用类型,传递的是该参数所引用的对象在堆中地址值的拷贝

ref > https://www.zhihu.com/question/31203609

原文地址:https://www.cnblogs.com/lwmp/p/10650746.html