传引用&传值

来源:互联网 发布:节奏大师网络拦截 编辑:程序博客网 时间:2024/06/12 21:58

下面的程序阐述了值传递与应用传递的区别。

package com.liaojianya.chapter1;/** * This program demonstrates the use of array reference. * @author LIAO JIANYA * 2016年7月21日 */public class ArrayReference{public static void main(String[] args){int x = 100;int arr[] = {1, 2, 3, 4, 5, 6};System.out.println("----------before invoking changeReferValue method-----------");print(x, arr);changeReferValue(x, arr);System.out.println("----------after invoking changeReferValue method-----------");print(x, arr);}public static void changeReferValue(int a, int[] chgArr){a += 1;chgArr[0] = 0;chgArr[1] = 0;chgArr[2] = 0;}public static void printArr(int[] arr){for(int i : arr){System.out.print(i + " ");}System.out.println();}public static void print(int x, int[] arr){System.out.println("x = " + x);System.out.print("arr: ");printArr(arr);}}

  运行结果:

----------before invoking changeReferValue method-----------x = 100arr: 1 2 3 4 5 6 ----------after invoking changeReferValue method-----------x = 100arr: 0 0 0 4 5 6 

  分析:

  1)由于整型形参a和实参x之间是值传递关系,所以不改变x的本身的值,只是在changeReferValue方法中,将x为100的这个值赋给了a,a += 1;后,是a 加了1,对x没有任何的影响。

  2)而对形参arr所指向的数组数据的任何修改,都会同步影响到main方法中的实参arr所指向的数组数据,这是英文传引用,实参和形参都是指向同一块内存空间。

0 0
原创粉丝点击