关于特定方法的JAVA

时间:2014-04-05 09:42:14

标签: java

我刚拿回我的Java试卷,有一个问题一直困扰着我。

有一个问题:

以下程序的输出是什么?

public class Swap {
    public static void swap(int[] a){
        int temp = a[1];
        a[1] = a[0];
        a[0] = temp;
    }

    public static void main(String[] args){
        int[] x = {5,3};
        swap(x);
        System.out.println("x[0]:" + x[0] + " x[1]:" + x[1]);
    }
}

我首先想到的是这是一个棘手的问题。由于swap方法返回类型为void,我认为它对int [] x数组没有影响。我的答案是x [0]:5 x [1]:3。我几乎可以肯定我得到了正确的答案,当我看到我被标记为错误时,我感到困惑。我去尝试NetBeans上的实际代码,并意识到数组中的值实际上已被交换!然后我继续测试是否是String的情况。我输入了类似但不同的代码:

public class Switch {
    public static void switch(String s){
        s = "GOODBYE";
    }

    public static void main(String[] args){
        String x = "HELLO";
        switch(x);
        System.out.println(x);
    }
}

输出仍然打印HELLO而不是GOODBYE。现在我的问题是为什么该方法不会更改String但它会更改数组中的值?

2 个答案:

答案 0 :(得分:2)

在Java中 - "对象的引用按值"。

传递
public class Swap {
    public static void swap(int[] a){  // now a = x --> {5,3}
        int temp = a[1]; 
        a[1] = a[0];     // swapping a[0] and a[1] in this and next step.
        a[0] = temp;
// NOW only a[] goes out of scope but since both x and a were pointing to the "same" object {5,3}, the changes made by a will be reflected in x i.e, in the main method.
    }

    public static void main(String[] args){
        int[] x = {5,3}; // here - x is a reference that points to an array {5,3}
        swap(x);   
        System.out.println("x[0]:" + x[0] + " x[1]:" + x[1]);
    }
}

public class Switch {
    public static void switch(String s){ // now s=x="Hello"
        s = "GOODBYE";   //here x="hello" , s ="GOODBYE"  i.e, you are changing "s" to point to a different String i.e, "GOODBYE", but "x" still points to "Hello"
    }
    public static void main(String[] args){
        String x = "HELLO";
        switch(x);
        System.out.println(x);
    }
}

答案 1 :(得分:2)

因为写s = "GOODBYE";只是将s指向另一个字符串。它不会更改原始String的值。

a[0] = something;a[1] = something;实际上是在弄乱a引用的数组,而不是将a指向不同的数组。

相关问题