值传递和引用传递

1、值传递

值传递的参数都是基本数据类型(如int、long和char等),在值传递里,所以的参数传递都采用值传递的方式,就是传递参数到方法时,方法获得的只是一个副本,所以方法不会改变参数变量的值,只是使用该参数变量的值(如果想要改变实际参数的值,可以把实际参数变为引用类型,变成引用传递就好了)

2、引用传递

引用传递指参数传递的是引用数据类型,则方法获得的是这个对象的内存地址,所以方法可以改变对象的属性,但不能改变对象本身

/**
 * 值传递
 */
public static void main(String[] args) {
    	int x = 10;
    	int y = 20;
    	System.out.println("传递前的值:x="+x+",y="+y);
    	add(x,y);
    	System.out.println("传递后的值:x="+x+",y="+y);
	}

	/**
	 * @param x
	 * @param y
	 */
	private static void add(int x, int y) {
		 int k = x+y;
		 y = x;
	     x = k;
	     System.out.println("add方法中的值:x="+x+",y="+y);
	}
}

运行结果:

传递前的值:x=10,y=20
add方法中的值:x=30,y=10
传递后的值:x=10,y=20
/**
 * 引用传递
 */
class Student {
	int number;
	public Student(int number) {
		this.number = number;
	}
}
public class TestDemo5 {
	public static void change(Student s) {
		s.number = 2000;
	}
    public static void main(String[] args) {
    	Student stu = new Student(10);
    	System.out.println("引用传递前:"+stu.number);
    	change(stu);
    	System.out.println("引用传递后:"+stu.number);
	}
}

运行结果:

引用传递前:10
引用传递后:2000

引用传递过程解析:
在程序执行到Student stu = new Student(10)时,分别在栈内存(储存对象的引用)和堆内存(储存对象)开辟空间供对象stu使用,程序执行到change()方法时,将对象stu的副本作为参数传递到change()方法,形参与实参指向同一地址,即同一对象,change()方法通过形参堆stu对象的属性number进行操作并改变了number的值,这一改变结果保留在对象中,但change()方法执行结束后,形参的引用被断开,但stu还是指向已经被改变的对象,所以最好stu.number=2000;

这里写图片描述

但是注意:
String用于引用传递,传形参后,执行完方法,变量的值并不会改变,这是因为String不可变的特性;

public class Test2 {
    public static void main(String[] args) {
        String s = "诸葛亮";
        System.out.println("引用传递前:"+s+"----"+System.identityHashCode(s));//获取当前对象的引用地址
        change(s);
        System.out.println("引用传递后:"+s+"----"+System.identityHashCode(s));

    }

    public static void change(String s) {
        System.out.println("方法里面:"+s+"----"+System.identityHashCode(s));
        s = "司马懿";
        System.out.println("方法里面:"+s+"----"+System.identityHashCode(s));
    }
}

运行结果:

引用传递前:诸葛亮----5896993
方法里面:诸葛亮----5896993
方法里面:司马懿----24537094
引用传递后:诸葛亮----5896993

版权声明:本文为QQ2899349953原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。