码迷,mamicode.com
首页 > 其他好文 > 详细

引用传递&值传递

时间:2016-07-21 21:58:12      阅读:249      评论:0      收藏:0      [点我收藏+]

标签:

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

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 = 100
arr: 1 2 3 4 5 6 
----------after invoking changeReferValue method-----------
x = 100
arr: 0 0 0 4 5 6 

  分析:

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

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

引用传递&值传递

标签:

原文地址:http://www.cnblogs.com/Andya/p/5693040.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!