The formal parameters of the method

 1 package basic.java;
 2 
 3 public class ParametersOfTheMethod {
 4     public static void main(String[] args) {
 5         int a = 10;
 6         int b = 20;
 7 
 8         System.out.println(a + "===" + b);
 9 
10         change(a, b);
11 
12         System.out.println(a + "===" + b);
13     }
14 
15     public static void change(int a, int b) {
16         // TODO Auto-generated method stub
17         System.out.println(a + "===" + b);
18         a = b;
19         b = a + b;
20         System.out.println(a + "===" + b);
21     }
22 
23 }

如果方法的参数是基本数据类型:形式参数的改变不影响实际参数。

 1 package basic.java;
 2 
 3 public class ArgsDemo2 {
 4     public static void main(String[] args) {
 5         int arr[] = { 1, 2, 3, 4, 5 };
 6 
 7         for (int i = 0; i < arr.length; i++) {
 8             System.out.println(arr[i]);
 9         }
10 
11         change(arr);
12 
13         for (int i = 0; i < arr.length; i++) {
14             System.out.println(arr[i]);
15         }
16     }
17 
18     public static void change(int[] arr) {
19         // TODO Auto-generated method stub
20         for (int i = 0; i < arr.length; i++) {
21             if (0 == arr[i] % 2) {
22                 arr[i] *= 2;
23             }
24         }
25     }
26 }

如果参数是引用数据类型:形式参数的改变直接影响实际参数。

猜你喜欢

转载自www.cnblogs.com/lzp123456-/p/9704104.html