深入理解String

String类型字符串是一个不可变量,一旦赋值后便不可改变值内容,但可改变引用地址。

String两种赋值方式的区别

①String a=“a”;这种方式会先在字符串常量池寻找是否有字符串a,有的话就引用其地址,否则新建(new String())并返回新的引用地址。如下的地址是相等的。

String a="a";
String b="a";
//String b="c"等价于String b=new String(c);
if(a==b)System.out.println(true);
else System.out.println(false);

②String a=new String(“a”)这种方式直接新开辟一个内存空间存放字符串,每次都会返回新地址,如下返回false;

String a=new String("a");
String b=new String("a");
if(a==b)System.out.println(true);
else System.out.println(false);

String类型字符串是一个不可变量,一旦赋值后便不可改变值内容。

public class Main {
    public static void main(String[] args) throws InterruptedException {
	String b = "a";
	String d = b;
	String e = b;
	if (d == e)
	    System.out.println(true);
	else
	    System.out.println(false);
    }
}

输出结果:true
再来看以下

public class Main {
    public static void main(String[] args) throws InterruptedException {
	String b = "a";
	String d = b;
	b="b";//改变b的值,在常量池找不到"b",则新建b=new String("b"),新建了一个String类型,b的引用地址改变
	String e = b;
	if (d == e)
	    System.out.println(true);
	else
	    System.out.println(false);
    }
}

此时输出结果:false
由此得出结论:String类型是不可变量,但重新赋值后其实是重新new了一个String,然后返回新的引用地址。这也可以解释为什么当一个String作为参数传入方法中改变值后,原先的值不改变。

public static void main(String[] args) throws InterruptedException {
	String a = "1";
	if (a == changString(a))
	    System.out.println(true);
	else
	    System.out.print(false);
    }

    private static String changString(String str) {
	// str = "2";// 该种赋值方式,常量池无"2",新建字符串,返回新地址,结果false
	// str = "1";// 常量池存在字符串"1",结果true
	// str = new String("1");// 该种赋值方式直接新建字符串,返回新地址,结果false
	// str = new String("2");// 该种赋值方式直接新建字符串,返回新地址,结果false
	return str;
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值