面试题1,值传递和参数传递

1,值传递和参数传递的区别?

答:值传递:方法调用时,实际参数把它的值传递给对应的形式参数,方法执行中形式参数值的改变不影响实际参数的值。

引用传递:也称为传地址。方法调用时,实际参数的引用(地址,而不是参数的值)被传递给方法中相对应的形式参数,在方法执行中,对形式参数

的操作实际上就是对实际参数的操作,方式执行中形式参数值的改变将会影响实际参数的值。

而在java中只有值传递,基本类型传递的是值的副本,引用类型传递(不是上面的那个)的是应用的副本。

public class testValue {

    public static void main(String[] args) {
        int i=3;
        int j=4;
        change(i,j);
        System.out.println("i的值为:"+i+"    j的值为:"+j);
    }

    static void change(int i,int j){
        int temp = i;
        i = j;
        j = temp;
    }
}

输出为:

i的值为:3    j的值为:4

i和j的结果并没有互换,因为参数中传递的是基本数据类型i和j的副本,不是数据的本身。

public class TestValue1 {

    public static void change(int[] count){
        count[0]=10;
    }

    public static void main(String[] args) {
        int[] count = {1,2,3,4,5};
        change(count);
        System.out.println(count[0]);
    }
}

这个也是引用count的副本

public class Student {
    private float score;

    public Student(float score) {
        this.score = score;
    }

    public float getScore() {
        return score;
    }

    public void setScore(float score) {
        this.score = score;
    }
}
public class ParamTest {
    public static void main(String[] args) {
        Student a = new Student(0);
        Student b = new Student(100);
        System.out.println("交换前:");
        System.out.println("a的分数:"+a.getScore()+"-----------b的分数:"+b.getScore());

        swap(a,b);



        System.out.println("交换后:");
        System.out.println("a的分数:"+a.getScore()+"-----------b的分数:"+b.getScore());
    }

    public static void swap(Student x,Student y){
        Student temp = x;
        x = y;
        y = temp;
    }
}

swap的调用过程:

1,将对象a,b的拷贝,还是值传递,本质和之前的两个例子是一样的。a和b指向的是不同的堆内存空间。

原文https://www.cnblogs.com/volcan1/p/7003440.html

posted @ 2018-12-19 14:22  正能量教官  阅读(379)  评论(0编辑  收藏  举报