zoukankan      html  css  js  c++  java
  • 引用传递&值传递

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

    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所指向的数组数据,这是英文传引用,实参和形参都是指向同一块内存空间。

  • 相关阅读:
    XML-Signature 语法和签名
    ZooKeeper相关资料集锦
    分布式锁
    spring-boot 知识集锦
    Spring boot druid 多数据源配置
    常见 SQL 语句的加锁分析
    fastjson反序列化多层嵌套泛型类与java中的Type类型
    Clean ThreadLocals
    java AOP Before, After, AfterReturning, AfterThrowing, or Around 注解
    java 线程间的通信 (wait / notify / notifyAll)
  • 原文地址:https://www.cnblogs.com/Andya/p/5693040.html
Copyright © 2011-2022 走看看