/*交换两个数值*/
public class SwapDemo {
/*public static void swap(int a,int b){
int temp=a;
a=b;
b=temp;
}*/
public static void main(String[] args) {
int first=10;
int second=20;
// 传递拷贝进去,方法内是将拷贝的值改变了
// 但不影响原来的参数a 和 b
swap(first,second);
System.out.println("first:"+first+"***"+"second:"+second);
}
}
在java中以上这种方式是无法进行两个数值交换的,这样写只是改变了形参的值,并没有改变实参的值
要想改变数值,如下:
1.
/*通过传入数组进行交换*/
public class SwapDemo2 {
public static void swap(int[] arr){
int temp=arr[0];
arr[0]=arr[1];
arr[1]=temp;
}
public static void main(String[] args) {
int[] nums=new int[2];
nums[0]=10;
nums[1]=20;
swap(nums);
System.out.println(nums[0]+" "+nums[1]);
}
}
package tree;
/*构造对象,将a,b作为对象的属性,然后操作对象,最后获得对应的属性。*/
public class SwapDemo3 {
public static void main(String[] args) {
int x = 10;
int y = 20;
Swap s = new Swap(x, y);
s.swap(s);
x = s.getA();
y = s.getB();
System.out.println("x:" + x + " " + "y:" + y);
}
}
class Swap {
private int a;
private int b;
public Swap(int a, int b) {
this.a = a;
this.b = b;
}
public int getA() {
return a;
}
public int getB() {
return b;
}
public void swap(Swap s) {
int temp = s.a;
a = s.b;
b = temp;
}
}