关于JAVA是值传递还是引用传递的问题

1.概念

  值传递:方法调用时,实际传入的是它的副本,在方法中对值的修改,不影响调用者的值。

  引用传递:方法调用时,实际传入的是参数的实际内存地址,调用者和调用方法所操作的参数都指向同一内存地址,所以方法中操作会影响调用者。

2.问题

  ① 值传递传入的值,是它的副本是什么意思?

  

public static void main(String[] args) {
        int a = 0;
     testValue(a); System.out.println(a); }
public void testValue(int a) { a = 8; }

  打印结果: 0

      此处调用方法后,a的值依然没有变化。

  

  ②当传入的值是一个对象时,也不会发生变化么?

package com.test;

public class TestDemo {
    public static void main(String[] args) {
        TestDemo2 testDemo2 = new TestDemo2();
        System.out.println("调用前:" + testDemo2.hashCode());
        testValue(testDemo2);
        System.out.println("调用后:" + testDemo2.hashCode());
    }
    
    public static void testValue(TestDemo2 testDemo) {
        testDemo = new TestDemo2();
    }
}

class TestDemo2 {
    int age = 1;
}

  打印结果:

   调用前:366712642
   调用后:366712642

  这里可以看到testDemo2 的值依然没有变化,调用前后所指向的内存地址值是一样的。对传入地址值的改变并不会影响原来的参数。

  ③既然是值传递,为什么参数是引用类型的时候,方法内对对象进行操作会影响原来对象,这真的是值传递么?

 

package com.test;

public class TestDemo {
    public static void main(String[] args) {
        TestDemo2 testDemo2 = new TestDemo2();
        System.out.println("调用前:" + testDemo2.age);
        testValue(testDemo2);
        System.out.println("调用后:" + testDemo2.age);
    }
    
    public static void testValue(TestDemo2 testDemo) {
        testDemo.age = 9;
    }
}

class TestDemo2 {
    int age = 1;
}

打印结果

调用前:1
调用后:9

 对于这种情况的解释是,传入的参数是testDemo2 对象地址值的一个拷贝,但是形参和实参的值都是一样的,都指向同一个对象,所以对象内容的改变会影响到实参。

综上所述:JAVA的参数传递确实是值传递,不管是基本参数类型还是引用类型,形参值的改变都不会影响实参的值。如果是引用类型,形参值所对应的对象内部值的改变

会影响到实参。

如有疑问或写的不恰当的地方欢迎在评论区指出!!

猜你喜欢

转载自www.cnblogs.com/chenfei-java/p/10657277.html