美文网首页
Java按值还是引用传参

Java按值还是引用传参

作者: 0x70e8 | 来源:发表于2018-03-23 22:40 被阅读0次

Java的方法参数是按值传递的

基本类型传递的是字面值,引用类型传递的是地址值。
也可以理解成,基本类型按值传递,引用类型按引用传递。

为什么

例子:

  • 例1
    @Test
    public void testPara1() {
        int a = 100, b;
        b = modBaseType(a);
        System.out.println(a);  // 100
        System.out.println(b);  // 101

    }

    int modBaseType(int n) {
        n += 1;
        return n;
    }
  • 例2
@Test
    public void testPara2() {
        int[] a = { 1, 2, 3, 4 }, na;
        na = modArray(a);
        printArray(a);  // 2018 2018 2018 2018 
        printArray(na); //2018 2018 2018 2018 

    }
    void printArray(int[] array) {
        for (int item : array) {
            System.out.print(item + " ");
        }
        System.out.println();
    }

    int[] modArray(int[] array) {
        for (int i = 0; i < array.length; i++) {
            array[i] = 2018;
        }
        return array;
    }
  • 例3
    @Test
    public void testPara3() {
        ClassWithMutableProperty c = new ClassWithMutableProperty(),nc;
        nc=modCWMP(c);
        System.out.println(c.getN()); // 1000
        System.out.println(nc.getN()); // 1000
        
    }

    ClassWithMutableProperty modCWMP(ClassWithMutableProperty obj) {
        obj.setN(1000);
        return obj;
    }
  • 例4
    @Test
    public void testPara4() {
        String s = "hello", ns;
        ns = modS(s);
        System.out.println(s); // hello
        System.out.println(ns); // helloworld
    }

    String modS(String s) {
        return s += "world";
    }

上面四个例子,实际上是三类,1是基本数据类型,2,3是对象本身提供了修改自己属性的方法,4是对象未提供修改自身的方法。
在例1中,实参把数值传给形参,之后便再无瓜葛。
例2和3以及例4中,实参把对象的地址传给形参,变成以下这样:


参数传递

如果对象本身可变,那对其作出的更改操作都将反映到实参和形参上,因为他们指向同一个地址。

相关文章

网友评论

      本文标题:Java按值还是引用传参

      本文链接:https://www.haomeiwen.com/subject/ywlfcftx.html