今天看到某互联网巨头的面试题,
private void foo()
{
String a ="123";
String b = new String("123");
}
问 字符串a,b分配在哪里?
答案是 都分配在栈里,因为他们运行在函数中。
我很怀疑这个面试官是不是装b。
首先 java的字符串常量,就是字面量 都分配在虚拟机的常量池(runtime constant pool)中,如果不信的话,你可以看java中密码不允许使用string,而是用char array。字符串字面量不会存放在栈中,它会存放在permanent generation中,一般不会垃圾回收。
其实full gc的时候,还是会回收的,只是string不会被回收。
不过从java 7开始,string分配会堆上。
Synopsis: In JDK 7, interned strings are no longer allocated in the permanent generation of the Java heap, but are instead allocated in the main part of the Java heap (known as the young and old generations), along with the other objects created by the application. This change will result in more data residing in the main Java heap, and less data in the permanent generation, and thus may require heap sizes to be adjusted. Most applications will see only relatively small differences in heap usage due to this change, but larger applications that load many classes or make heavy use of the String.intern() method will see more significant differences.
大公司的面试官只会装b
阅读(2689) | 评论(0) | 转发(0) |