java的值传递

来源:互联网 发布:it人才需求 编辑:程序博客网 时间:2024/05/16 19:00
在Oracle的技术面的时候居然被问了java中的函数传递类型,我很清楚的知道是值传递,也知道要分基本类型和对象两种情况来解释,不过在说到对象的时候却怎么也想不明白了估计这个对我面试的结果影响会很大 呵呵,过会写个Oracle技术类的面经吧.

首先还是对于一个基本类型的变量来说,比如 int,char类型的变量,传入函数的那个是该基本类型的值,也就是说在函数体中是改变不了传入的这个参数的值的.

public void changeInt(int i) {
        i = 0;
}

public static void main(String[] args) {
        int i = 1;
        System.out.println("before the change , i = " + i);
        changeInt(i);
       
System.out.println("after the change , i = " + i);
}

结果都是1.

对于传入的参数是一个类的对象的话,为什么还是值传递呢?
从我在网上搜到的东西和我自己的理解来看,主要是这样的, 传入的参数所代表的对象就是一个



可是如果是如果变量是一个类类型的呢?那它的值是什么呢?它的值就是它的引用,传入的就是对象的句柄,我们不能改变对象本身的值,当时对传入的参数所做的修改是对该句柄指向对象的修改,这样的话 ,对象具体内容也被改变了.

public class ValueTest {

    public static void changeString(String s) {
        s = "helloworld";
    }
   
    public static void main(String[] args) {
        String testStr = "Hiworld";
        System.out.println("before change the string is " + testStr);
        changeString(testStr);
        System.out.println("after change the string is " + testStr);
    }
}

结果都是Hiworld.

这个应该是因为String是个final的类,所以
        s = "helloworld"; 是将s指向了另一个对象.

对于一些其他非final的对象来说

public class Valuetest {

    public static void changeDate(Date d) {
        d.setTime(1L);
    }
   
    public static void main(String[] args) {
        Date d = new Date();
        System.out.println(d.getTime());
       
changeDate(d);
        System.out.println(d.getTime());
    }
}

结果就是

1166586775750
1

第一个是当前时间的毫秒数.
在这个例子中
changeDate调用了date的一个函数修改了d的一个属性,就对传入的原来的参数起了作用..


说的不是很清楚 不过看程序应该能明白是什么意思了吧.