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);
}
}
- 結果: 示例:
- 示例代碼
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);
}
}
- 結果 示例:
- 示例代碼
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);
}
}
- 結果