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的值都不会发生变化。
- 结果:
示例:
- 示例代码
public class DemoTest {
public static void fun(String s) {
System.out.println("fun1 " + s);
s = "lisi";
System.out.println("fun2 " + s);
}
public static void main(String[] args) {
String a = "zhangsan";
fun(a);
System.out.println(a);
}
}
- 结果
- 实体类
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的值也发生了相应的变化。
- 结果
示例:
- 示例代码
public class ABCD {
public static void fun(Date d) {
System.out.println("fun1 " + d);
try {
Thread.sleep(2000);
} catch (Exception e) {
System.out.println("错了");
}
d = new Date(); //① new 强制开辟空间
System.out.println("fun2 " + d);
}
public static void main(String[] args) {
Date date = new Date();
fun(date);
System.out.println(date);
}
}
注意:编号①位置处的new强制开辟了新的空间,并让形参指向了该新空间,所以没有修改到main中的date的值。
- 结果