1

Hi i am working in java and want to know how String objects are created in the String pool and how they are managed.

So in the following example i am creating two Strings s and s1,so can anyone explain me how many Objects are created in LIne1?Also how many Objects are eligible for garbage collection in Line3?

  String s = "x" + "y";//Line 1
  String s1 = s;//Line 2
  s = null;//Line 3
4

2 回答 2

3

只创建一个对象"xy"。编译器这样做是为了优化。

没有对象有资格进行垃圾回收。

于 2013-04-20T20:09:43.290 回答
0

它将xy在字符串常量池区域中创建一个对象。正如"x"+"y"在编译期间评估的那样。此外,垃圾收集器无法访问字符串常量池区域。

参考:https ://docs.oracle.com/javase/specs/jls/se7/html/jls-3.html#jls-3.10.5

于 2019-05-10T15:04:42.947 回答