Java引用

例1:

package com.jike.reference;
class Ref1{
	int temp = 10;
}
public class test01 {

	public static void main(String[] args) {
		Ref1 r1 =new Ref1();
		r1.temp = 20;
		System.out.println(r1.temp);
		tell(r1);
		System.out.println(r1.temp);
	}
	public static void tell(Ref1 r2){
		r2.temp = 30;
	}
}

 输出:

20
30

 例2:

package com.jike.reference;

public class test02 {
	public static void main(String[] args) {
		String str1 = "Hello";
		System.out.println(str1);
		tell(str1);
		System.out.println(str1);
	}
	public static void tell(String str2){
		str2="jike";
	}
}

 输出:

Hello
Hello

 string类型的变量str1不会被改变,str2="jike"会在堆中开辟另一个新的内存地址存放“jike”,原本的str1仍然指向"Hello"。

例3:

package com.jike.reference;
class Ref2{
	String temp = "hello";
}
public class test03 {

	public static void main(String[] args) {
		Ref2  r1 = new Ref2();
		r1.temp="jike";
		System.out.println(r1.temp);
		tell(r1);
		System.out.println(r1.temp);
	}
	public static void tell(Ref2  r2){
		r2.temp="xueyuan";
	}
}

 输出:

jike
xueyuan

 例1和例3是相同类型的,例2涉及到string类型有些特殊。

原文地址:https://www.cnblogs.com/zhhy236400/p/10438307.html