【问题标题】:String objects and storage [duplicate]字符串对象和存储[重复]
【发布时间】:2020-01-03 15:52:52
【问题描述】:

以下代码将创建多少个对象以及它们将存储在哪里?

String s = "abc"; // line 1
String s1 = new String("abc"); // line 2
String str1 = new String("efg"); //line 3

【问题讨论】:

  • 将创建 3 个对象,1 个在 SCP,2 个在堆中
  • 您的最佳猜测是什么?为什么?
  • 搜索how many strings created 会产生很多类似的问题。
  • @Deadpool 请原谅,但我不会说 newspeak SCP 意思是“字符串常量池”吗?
  • 不会“efg”也存储在字符串池中吗?

标签: java string heap-memory string-pool


【解决方案1】:
Total 3 objects will be created.    
Line 1 : Object will be created in string pool,
Line 2 : Object will be created in Heap,
Line 3 : Object will be created in Heap.

Reason is : 
a) By string literal : Java String literal is created by using double quotes like in line 1. It is always created in String pool,
b) By new keyword : Java String is created by using a keyword “new” like in line 2 and 3.  It is always created in Heap memory.

供参考: https://www.geeksforgeeks.org/string-initialization-java-string-literal-vs-string-object/

【讨论】:

    猜你喜欢
    • 2012-12-30
    • 1970-01-01
    • 2013-12-02
    • 1970-01-01
    • 1970-01-01
    • 2018-10-17
    • 2013-09-14
    • 2019-02-01
    • 2011-03-18
    相关资源
    最近更新 更多