关于特定方法的JAVA
我刚拿回我的Java试卷,有一个问题一直困扰着我 有一个问题: 以下程序的输出是什么关于特定方法的JAVA,java,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};
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]:5x[1]:3。我几乎可以肯定我得到了正确的答案,当我看到自己被标记为错误时,我感到困惑。我尝试了NetBeans上的实际代码,并意识到数组中的值实际上被交换了!然后我继续测试字符串是否是这样。我输入了一个类似但不同的代码:
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而不是再见。现在我的问题是,为什么该方法不更改字符串,而是更改数组中的值?在Java中,“对对象的引用是按值传递的”
以及
因为写s=“再见”代码>仅将s
指向不同的字符串。它不会更改原始字符串的值
而写a[0]=something代码>或a[1]=某物
实际上是在与a
引用的数组混在一起,但没有将a
指向另一个数组。哦!这是有道理的。谢谢你的回答~终于可以把这个难题从我的脑海中弄出来了。@user3312742-不客气:)
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);
}
}