基本数据类型与引用数据类型参数
1 package day05; 2 3 public class MethodDemo06 { 4 /*方法参数传递为基本数据类型:传入方法中的是具体的数值*/ 5 public static void main(String[] args) { 6 int number = 100; 7 System.out.println("调用change方法前:" + number); 8 number = 200; 9 change(number); 10 System.out.println("调用change方法后:" + number); 11 12 } 13 14 public static int change(int number) { 15 return number; 16 } 17 }
执行结果:
方法参数为引用数据类型:
1 package day05; 2 3 public class MethodDemo07 { 4 /*方法参数传递为引用类型:传入方法中的是内存地址*/ 5 public static void main(String[] args) { 6 int[] arr = {12, 22, 40}; 7 System.out.println("调用change方法前:" + arr[1]); 8 change(arr); 9 System.out.println("调用change方法后:" + arr[1]); 10 } 11 12 public static void change(int[] arr) { 13 arr[1] = 20; 14 } 15 }
执行结果:
eg:
1 package day05; 2 3 public class MethodDemo08 { 4 public static void main(String[] args) { 5 int[] arr = {1, 2, 3, 5, 34}; 6 int max = getMax(arr); 7 System.out.println(max); 8 } 9 10 public static int getMax(int[] arr) { 11 int max = arr[0]; 12 for (int i = 1; i < arr.length; i++) { 13 if (max < arr[i]) { 14 max = arr[i]; 15 } 16 } 17 return max; 18 } 19 }
执行结果:
eg:
package day05;
public class MethodDemo09 {
public static void main(String[] args) {
int[] arr = {23, 32, 11, 12};
System.out.println("代码逻辑");
printArray(arr);
System.out.println();
}
public static void printArray(int[] arr) {
System.out.print("[");
for (int i = 0; i < arr.length; i++) {
if (i == arr.length - 1) {
System.out.print(arr[i] + "]");
} else {
System.out.print(arr[i] + ",");
}
}
}
}
执行结果:
eg:
1 package day05; 2 3 public class MethodDemo10 { 4 public static void main(String[] args) { 5 int[] arr = {11, 24, 13, 34, 25}; 6 int[] maxAndMin = getMaxAndMin(arr); 7 System.out.println(maxAndMin[0]); 8 System.out.println(maxAndMin[1]); 9 } 10 11 public static int[] getMaxAndMin(int[] arr) { 12 int max = arr[0]; 13 for (int i = 1; i < arr.length; i++) { 14 if (max < arr[i]) { 15 max = arr[i]; 16 } 17 } 18 int min = arr[0]; 19 for (int i = 1; i < arr.length; i++) { 20 if (min > arr[i]) { 21 min = arr[i]; 22 } 23 } 24 int[] maxAndMin = {min, max}; 25 return maxAndMin; 26 } 27 }
执行结果:
欢迎批评指正,提出问题,谢谢!