java方法參數的傳遞有兩種,值傳遞和引用傳遞。
1.按值傳遞:
參數類型是int,long等八大基本數據類型時,參數傳遞的過程是按值拷貝的過程
如下代碼
1
2
3
4
5
6
7
8
9
|
public static void main(String[] args) { int a = 5 ; fun(a); System.out.println(a); // 輸出結果為5 } private static void fun( int a) { a += 1 ; } |
2.按引用傳遞
參數類型為引用類型,參數傳遞的過程采用拷貝引用的方式
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
|
public class Test { public static void main(String[] args) { A a = new A( 5 ); fun(a); System.out.println(a.a); // 輸出結果為6 } private static void fun(A a) { a.a += 1 ; } static class A { public int a; public A( int a) { this .a = a; } } } |
再看下面這種情況:
1
2
3
4
5
6
7
8
9
10
|
public class Test { public static void main(String[] args) { Integer a = 5 ; fun(a); System.out.println(a); // 輸出結果為5 } private static void fun(Integer a) { a += 1 ; } } |
這里明明是引用傳遞,為什么沒有改變對象的值呢?
這里其實使用了基本數據類型封裝類的自動裝箱功能。
Integer a = 5,編譯后實際為Integer a = Integer.valueOf(5),查看Integer的源碼,并沒有改變原對象的值,只是將其引用指向了另一個對象。
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持服務器之家。
原文鏈接:https://www.cnblogs.com/linwenbin/p/12308245.html