【问题标题】:What happens with these string concatenations? [closed]这些字符串连接会发生什么? [关闭]
【发布时间】:2013-07-09 14:00:01
【问题描述】:

问题- 下面的字符串在字符串池中连接后占用内存的位置,答案是什么,为什么?

public class Test1234 { 
    public static void main(String[] args) { 
         final String s1="jlc"; 
         final String s2="india"; 
         String s3=s1+s2; String s4="jlcindia"; 
         System.out.println(s3==s4); 
   } 
 }

【问题讨论】:

  • 这个问题似乎离题了,因为您没有表现出任何解决问题的努力。
  • 你怎么想,为什么?
  • 据我所知,字符串连接是在编译时完成的......

标签: java core


【解决方案1】:

它将打印true,因为s1 和s2 是字符串文字并被声明为final,因此s3 = s1 + s2 被视为常量并在编译时解析。因此,s3 和 s4 将引用字符串池中的相同字符串。

如果您删除了那些 final 关键字,它将打印 false。

【讨论】:

  • 公共类 Test1234 { public static void main(String[] args) { String s1="jlc";字符串 s2="印度";最终字符串 s3=s1+s2;字符串 s4="jlcindia"; System.out.println(s3==s4); } } 在这种情况下,我们还连接了一个最终的字符串变量,因此 s3 应该具有常量值并驻留在字符串池中,但是在比较 s3 和 s4 时会给出错误的原因????
  • @user2564712 因为s1和s2不是final,所以s3在编译时没有解析。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-12-18
  • 1970-01-01
  • 1970-01-01
  • 2017-02-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多