这两种初始化String的方式有什么区别? [英] What is the difference between these two ways of initializing a String?

查看:54
本文介绍了这两种初始化String的方式有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

String obj = null;
obj= new String("Samuel");

//vs

String obj = null;
obj="Samuel";

这两种初始化String的方式之间是否有区别?

Is there any difference between these two ways of initializing a String?

推荐答案

String obj = new String("Samuel");
String obj1 = new String("Samuel");

//vs

String obj = "Samuel";
String obj1 = "Samuel";

在第一种情况下 obj == obj1 返回false

in the first case obj==obj1 returns false

在第二种情况下, obj == obj1 返回true.

in the second case obj==obj1 returns true.

这样做的原因是,在第一种情况下,您有两个对两个不同对象的引用.在第二种情况下,您有一个对象,因为字符串是不可变的,它们是 interned 并从同一对象中提取池.

The reason for that is that in the first case you have two references to two different Objects. In the second case you have one object since Strings are immutable they are interned and drawn from the same pool.

这篇关于这两种初始化String的方式有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆