字符串对象和存储

时间:2020-01-03 15:52:52

标签: java string heap-memory string-pool

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

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

1 个答案:

答案 0 :(得分:0)

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/

相关问题