【问题标题】:How many String objects will be created in String s="Sachin"+" Tendulkar"; [duplicate]在 String s="Sachin"+" Tendulkar" 中将创建多少个 String 对象; [复制]
【发布时间】:2014-02-03 11:54:27
【问题描述】:

在声明 String s="Sachin"+" Tendulkar" 中创建了多少个 String 对象; ?这是我的面试题

【问题讨论】:

  • 很好的面试问题。

标签: java


【解决方案1】:
how many String objects are created in the above declaration? 
This is my interview question
  • "Sachin" -> 字符串字面量

  • "Tendulkar" -> 字符串字面量

只有一个String s 是由两个文字的串联创建的

【讨论】:

    【解决方案2】:

    String s=“Sachin”+“ Tendulkar”; 只限一个

    【讨论】:

      【解决方案3】:
      Strings computed by constant expressions are computed at compile time and then
      treated as if they were literals. 
      

      规格:here

      String s="Sachin"+" Tendulkar";
      

      因此,如果您指定只会创建一个字符串文字(在编译时本身创建),即"SachinTendulkar"。因此,字符串池中将只有一个实习字符串。

      如果您尝试连接单独的显式文字,那么只有您将在字符串池中拥有单独的实习对象。例如。

      String s1 = "Sachin";
      String s2 = "Tendulkar";
      String s3 = s1 + s2;
      

      在上述情况下,字符串池中将有 3 个不同的实习对象。

      【讨论】:

      • 一点澄清。在最后一种情况下,字符串池中只有 2 个不同的实习对象(s1,s2),堆(s3)中只有 1 个对象,因为变量的连接是使用 StringBuilder.append 执行的,然后是内部使用 new String()
      猜你喜欢
      • 2014-11-26
      • 1970-01-01
      • 1970-01-01
      • 2018-04-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多