关于Java字符串String在运算中的拼接

看代码不解释。

        String s1 = "a";
        String s2 = "b";
        String s3 = s1 + s2;
        String s4 = s1 + s2;
        System.out.println(s3 == s4);
        System.out.println(s3.equals(s4));
        String s5 = "a";
        System.out.println(s1 == s5);

看结果:

false
true
true

关于Java实现的步骤如下:
查看字符串常量池中是否存在相同的字符串对象。
若没有,则新创建一个包含该内容的字符串对象,并让引用变量指向该对象。例如,创建字符串s1的时候,字符串常量池中没有,则创建一个新对象,并让引用s1指向该对象。
若已经存在包含该内容的字符串对象,则让字符串引用直接指向该对象。例如,在创建字符串s5的时候,字符串常量池中已经有包含该内容的对象了,所以引用s2直接指向已有的对象。
如果是运算中拼接的,在常量池中是不存在的。如上结果可知。
增加代码:

System.out.println("--------------------------------");
        String s6 = new String("a");
        System.out.println(s1 == s6);
        System.out.println(s1.equals(s2));

看结果:

--------------------------------
false
true

自然new出来的,在堆中新开辟了一个地址,栈中的对象指向它
继续修改代码:

System.out.println("*********************************");
        String s6 = new String("a");
        System.out.println(s1 == s6);
        System.out.println(s1.equals(s6));
        System.out.println(s1.intern());
        System.out.println(s1.intern()==s6.intern());
        System.out.println(s1.intern()==s5.intern());

看结果

*********************************
false
true
a
true
true

关于Intern方法
查看jdk源码


Returns a canonical representation for the string object.
A pool of strings, initially empty, is maintained privately by the class String.

When the intern method is invoked, if the pool already contains a string equal to this String object as determined by the equals(Object) method, then the string from the pool is returned. Otherwise, this String object is added to the pool and a reference to this String object is returned.

It follows that for any two strings s and t, s.intern() == t.intern() is true if and only if s.equals(t) is true.

这里强调了只要s.equals(t) is true ,所有上面的代码的结果自然就清楚了。

All literal strings and string-valued constant expressions are interned. String literals are defined in section 3.10.5 of the The Java™ Language Specification.

Returns:
a string that has the same contents as this string, but is guaranteed to be from a pool of unique strings.

附:jdk中文翻译:
intern
public String intern()返回字符串对象的规范化表示形式。
一个初始为空的字符串池,它由类 String 私有地维护。

当调用 intern 方法时,如果池已经包含一个等于此 String 对象的字符串(用 equals(Object) 方法确定),则返回池中的字符串。否则,将此 String 对象添加到池中,并返回此 String 对象的引用。

它遵循以下规则:对于任意两个字符串 s 和 t,当且仅当 s.equals(t) 为 true 时,s.intern() == t.intern() 才为 true。

所有字面值字符串和字符串赋值常量表达式都使用 intern 方法进行操作。字符串字面值在 Java Language Specification 的 §3.10.5 定义。
返回:
一个字符串,内容与此字符串相同,但一定取自具有唯一字符串的池。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值