值傳遞
當調用方法進行值傳遞時,方法內部會產生一個局部變量,在方法內部使用局部變量的值,并不影響傳入原來數據的值,包括在使用基本數據類型的包裝類。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
|
public class Assc { public static void main(String[] args) { int x1= 1 ; add(x1); System.out.println( "最終" +x1); //1 Integer x2= new Integer( 1 ); sub(x2); System.out.println( "最終" +x2); //1 } public static void add( int x) { x++; System.out.println(x); //2 } public static void sub(Integer x) { x--; System.out.println(x); //0 } } |
引用傳遞
當調用方法時使用引用類型參數時,使用的是與傳入參數同一地址的數據,在方法內部進行參數的修改,會造成原來數據的改變(String 類型除外)
String類型數據在傳入時,進行的操作是在字符串常量池中新建一個字符串,并不影響原先字符串的值
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
|
public class Assc { public static void main(String[] args) { String str= "hello" ; combine(str); System.out.println( "最終" +str); //hello StringBuilder sb= new StringBuilder( "nihao" ); combine2(sb); System.out.println( "最終" +sb); //nihaoworld } public static void combine(String str) { str+= "world" ; System.out.println(str); //helloworld } public static void combine2(StringBuilder str) { str.append( "world" ); System.out.println(str); //nihaoworld } } |
到此這篇關于java參數傳遞之值傳遞和引用傳遞的文章就介紹到這了,更多相關值傳遞和引用傳遞內容請搜索服務器之家以前的文章或繼續瀏覽下面的相關文章希望大家以后多多支持服務器之家!
原文鏈接:https://www.cnblogs.com/leohost/p/14388853.html