String 对象及常量池

  1. 首先String不属于8种基本数据类型,是一个对象,默认值为null,new String()和new String("")都是声明一个空字符串,而不是null。
  2. 面试时经常被问到:
    String s = “hello”;和String s = new String(“hello”);的区别。
    这里我们先说说常量池。

常量池是在编译期被确定,并被保存在已编译的.class文件中的一些数据。它包括了关于类、方法、接口等中的常量,也包括字符串常量

`	public static void main(String[] args) {
		String s1 = "hello";
		String s2 = "hello world";
		String s3 = s1+" world";
		String s4 = "hello"+" world";
		String  s5 =  new  String( "abc ");
		
		System.out.println(s2==s3); //false,实际上是new StringBuffer(s1).append(" world");
		System.out.println(s2==s4); //true
	}

“hello"和” world"都是字符串常量,它们在编译期就被确定了,多个字符串常量连接时,结果也是字符串常量,因此s2==s4。

而s5通过new创建字符串时,这里 "abc "本身就是pool中的一个对象,而在运行时执行new String()时,将pool中的对象复制一份放到heap中,并且把heap中的这个对象的引用交给s5持有。ok,这条语句就创建了2个String对象。

  1. intern()的意思:

当一个String实例str调用intern()方法时,Java查找常量池中是否有相同Unicode的字符串常量,如果有,则返回其的引用,如果没有,则在常量池中增加一个Unicode等于str的字符串并返回它的引用

 public static void main(String[] args) {
		String ss0 = "abc";
		String ss1 = new String("abc");
		System.out.println(ss0==ss1); // false
		ss1 = ss1.intern(); //查找常量池是否有abc的引用,如果有则返回,如果没有则创建
		System.out.println(ss0==ss1); // true
	}
```java



  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值