Java老是采用按值调用。方法获得的是全部参数值的一个拷贝,特别的,方法不能修改传递给它的任何参数变量的内容。java
方法参数共有两种类型:this
查看一下的代码:spa
public class ParamTest { public static void main(String[] args) { int price = 5; doubleValue(price); System.out.print(price); } public static void doubleValue(int x) { x = 2 * x; } }
【输出结果】: 5对象
能够看到,这个方法执行以后,price的值并无变化。接下来,看一下doubleValue具体的执行过程为:blog
从上面的例子咱们已经知道一个方法不能修改一个基本数据类型的参数。而对象引用做为参数就不一样了。看下面的例子:get
class Student { private float score; public Student(float score) { this.score = score; } public void setScore(float score) { this.score = score; } public float getScore() { return score; } } public class ParamTest { public static void main(String[] args) { Student stu = new Student(80); raiseScore(stu); System.out.print(stu.getScore()); } public static void raiseScore(Student s) { s.setScore(s.getScore() + 10); } }
【运行结果】:class
90.0变量
能够看出,Student实例s的内容改变了。数据类型
具体执行过程为:引用
首先编写一个交换两个学生的方法:
public static void swap(Student x, Student y) { Student temp = x; x = y; y = temp; }
若是java对对象是采用的是引用传递,那个这个方法是能够的。那么x,y对象的分数是交换的。看下面的例子:
class Student { private float score; public Student(float score) { this.score = score; } public void setScore(float score) { this.score = score; } public float getScore() { return score; } } public class ParamTest { public static void main(String[] args) { Student a = new Student(0); Student b = new Student(100); System.out.println("交换前:"); System.out.println("a的分数:" + a.getScore() + "--- b的分数:" + b.getScore()); swap(a, b); System.out.println("交换后:"); System.out.println("a的分数:" + a.getScore() + "--- b的分数:" + b.getScore()); } public static void swap(Student x, Student y) { Student temp = x; x = y; y = temp; } }
【运行结果】:
交换前:
a的分数:0.0--- b的分数:100.0
交换后:
a的分数:0.0--- b的分数:100.0
能够看出,二者并无实现交换。说明引用传递的说法是不正确的。接下来一步一步看看swap调用的过程:
首先,建立两个对象:
而后,进入方法体,将对象a,b的拷贝分别赋值给x,y:
接着,交换x,y的值:
swap执行完成,x,y再也不使用,回到建立时状态。
从这个过程当中能够看出,Java对对象采用的不是引用调用,实际上,对象引用进行的是值传递。
总结一下java中方法参数的使用状况: