Java方法传递参数大概分为传值
和传址
两种情况,下面分别通过具体的救命讲解。
- 传值:基本数据类型、String
- 传址:引用数据类型
传值
-
测试代码
public class DemoTest{ public static void fun(int a) { System.out.println("fun1 " + a); a = 88; System.out.println("fun2 " + a); } public static void main(String[] args) { int aa = 1234; fun(aa); System.out.println(aa); }
}
main方法中调用fun方法时,因为只是将aa的`数值`传递给了fun方法,所以在fun中不管怎么修改形参a的值,main中aa的值都不会发生变化。
- 结果:

## 传址
- 实体类
```java
public class Dept {
private int deptno;
public int getDeptno() {
return deptno;
}
public void setDeptno(int deptno) {
this.deptno = deptno;
}
public Dept() {
super();
// TODO Auto-generated constructor stub
}
public Dept(int deptno) {
super();
this.deptno = deptno;
}
@Override
public String toString() {
return "Dept [deptno=" + deptno + "]";
}
}
- 测试代码
public class DemoTest {
public static void main(String[] args) throws Exception {
Dept dept = new Dept(11);
fun(dept);
System.out.println(dept);
}
//方法中的参数是局部变量
public static void fun(Dept dept) {
System.out.println("fun1 " + dept);
dept.setDeptno(1234);
System.out.println("fun2 "+dept);
}
}
main方法中调用fun方法时,因为只是将dept的地址传递给了fun方法,所以在fun中修改dept的值,也就相当于修改main中dept的值,所以最终main中的dept的值也发生了相应的变化。
- 结果