Java基础笔记19——值传递与引用地址传递
一、值传递:
基本数据类型与String字符串类型均为值传递,方法中对参数的修改,不会影响传递之前的变量值
二、引用地址传递:
引用对象传递参数时,传递的为引用地址,方法中对参数的任意修改,将影响原参数的信息
三、例子:
package com.lqh.chapter01; import java.util.Arrays; public class _17zhichuandi { /** * 值传递,不影响main方法里的x的变量值 * * @param x */ public static void getX(int x) { x = 100; System.out.println("getX:" + x); } /** * 引用地址传递:影响main方法中的array的变量值 * * @param array */ public static void getArray(int[] array) { array[3] = 520; System.out.println("getArray:" + Arrays.toString(array)); } public static void main(String[] args) { // 1.值传递 int x = 2; getX(x); System.out.println("main:" + x); System.out.println("-----------------------"); // 2.引用地址传递 int[] array = new int[] { 1, 3, 4, 5, 6 }; getArray(array); System.out.println("main" + Arrays.toString(array)); } }
输出结果为:
getX:100
main:2
-----------------------
getArray:[1, 3, 4, 520, 6]
main[1, 3, 4, 520, 6]