探索String的集中赋值方式,以及一些关于String的练习

本文深入探讨了Java中String对象的创建方式及其与常量池的关系,通过多个示例解释了==和equals方法的区别,以及字符串拼接在不同情况下的表现。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

String s1 = new String("hello");
String s2 = "hello";
System.out.println(s1 == s2);// false
System.out.println(s1.equals(s2));// true
String s3 = String.valueOf("hello");
System.out.println(s3);
System.out.println(s3==s2);//true
System.out.println(s3==s1);//false

String s1 = new String("hello");

不管方法区常量池是否有"hello"存在,都会在堆内存new()一个新的String对象,如果常量池中存在该字符串,则该对象指向常量池中的字符串,否则在常量池中创建新的常量,然后该对象的地址值赋给s1变量。

 

String s2 = "hello";

String s3 = String.valueOf("hello")

从测试结果来看,都是现在常量池寻找,所以s2 == s3为true

 

其他练习:

                String s1 = new String("hello");
		String s2 = new String("hello");
		System.out.println(s1 == s2);// false
		System.out.println(s1.equals(s2));// true

		String s3 = new String("hello");
		String s4 = "hello";
		System.out.println(s3 == s4);// false
		System.out.println(s3.equals(s4));// true

		String s5 = "hello";
		String s6 = "hello";
		System.out.println(s5 == s6);// true
		System.out.println(s5.equals(s6));// true

练习2:

		String s1 = "hello";
		String s2 = "world";
		String s3 = "helloworld";
		System.out.println(s3 == s1 + s2);// false
		System.out.println(s3.equals((s1 + s2)));// true

		System.out.println(s3 == "hello" + "world");// false 这个我们错了,应该是true
		System.out.println(s3.equals("hello" + "world"));// true

解析:s1 + s2 在编译的时候是先在堆内存创建一个新的String对象,再把s1和s2拼接的结果赋给新对象,所以虽然s3和s1+s2的字符串内容一样,但是s3==s1+s2为false

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值