java-易错点

参数传递

传递基本数据类型时:

public class ArgumentsDemo01 {
    
    
	public static void main(String[] args) {
    
    
		int a=5;
		int b=10;
		change(a, b);//调用方法时,传入的数值称为实际参数
		System.out.println("a=" + a);
		System.out.println("b=" + b);
	}

	public static void change(int a, int b){
    
    //方法中指定的多个参数称为形式参数
		a=200;
		b=500;
	}
}

输出:
a=5
b=10

原因方法change运行完后空间清除,并不影响主方法中的a,b

传递引用数据类型时:

public class ArgumentsDemo02 {
    
    
	public static void main(String[] args) {
    
    
		int[] arr = {
    
     1, 2, 3 };
		change(arr);// 调用方法时,传入的数值称为实际参数
		
		for (int i = 0; i < arr.length; i++) {
    
    
			System.out.println(arr[i]);
		}
	}

	public static void change(int[] arr) {
    
    // 方法中指定的多个参数称为形式参数
		for (int i = 0; i < arr.length; i++) {
    
    
			arr[i] *= 2;
		}
	}
}

输出:
2
4
6

原因:传递参数时传递的是内存地址

猜你喜欢

转载自blog.csdn.net/xiaonuanhu/article/details/107716923
今日推荐