互换值
方法1:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
public class Change {
public static void change(int x,int y) {
System.out.println("改变之前");
System.out.println("x = "+x);
System.out.println("y = "+y);
int z;
z = x;
x = y;
y = z;
System.out.println("改变之后");
System.out.println("x = "+x);
System.out.println("y = "+y);
}
public static void main(String[] args) {
change(3,4);
}
}
![](https://pic002.cnblogs.com/images/2010/171363/2010122213083141.gif)
方法2:
对于基本数据类型传递的是数据的拷贝,而对于引用数据类型传递的是引用的拷贝。
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
// 此类不像方法1那样是用一个临时变量来保存
public class Change {
public static void change(int x,int y) {
x = x + y;
y = x - y;
x = x - y;
}
public static void change(int[] num) {
num[0] = num[0] + num[1];
num[1] = num[0] - num[1];
num[0] = num[0] - num[1];
}
public static void change(Point pt) {
pt.x = pt.x + pt.y;
pt.y = pt.x - pt.y;
pt.x = pt.x - pt.y;
}
public static void main(String[] args) {
int x = 3;
int y = 4;
change(x,y);
System.out.println("x = " + x);
System.out.println("y = " + y);
System.out.println();
int[] num = {3,4};
change(num);
System.out.println("x = " + num[0]);
System.out.println("y = " + num[1]);
System.out.println();
Point pt = new Point();
pt.x = 3;
pt.y = 4;
change(pt);
System.out.println("x = " + pt.x);
System.out.println("y = " + pt.y);
}
}
class Point {
int x,y;
}
![](https://pic002.cnblogs.com/images/2010/171363/2010122213123721.gif)