这些对我来说看起来是一样的,但为什么它们会产生不同的输出?我是 Java 新手,请耐心等待!
此交换功能有效
//Swap 1 Output is "4,8"
public class SampleSwap {
public static void main(String[] args)
{
int a=8;
int b=4;
int temp;
temp=a;
a=b;
b=temp;
System.out.println("a:" +a);
System.out.println("b:" +b);
}
}
此交换功能不起作用
//Swap 2 Output is "8,4"
public class Swap {
public static void main(String[] args) {
int a = 8, b = 4;
swap(a, b);
System.out.print(a + "," + b);
System.out.println();
}
public static void swap(int a, int b) {
int tmp = a;
a = b;
b = tmp;
}
}
最佳答案
这些参数是按值传递的。他们不会改变原来的内容。
关于java - Java 中的简单交换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32431061/