Chinaunix首页 | 论坛 | 博客
  • 博客访问: 4116880
  • 博文数量: 447
  • 博客积分: 1241
  • 博客等级: 中尉
  • 技术积分: 5786
  • 用 户 组: 普通用户
  • 注册时间: 2011-01-27 06:48
个人简介

读好书,交益友

文章分类

全部博文(447)

文章存档

2023年(6)

2022年(29)

2021年(49)

2020年(16)

2019年(15)

2018年(23)

2017年(67)

2016年(42)

2015年(51)

2014年(57)

2013年(52)

2012年(35)

2011年(5)

分类: Java

2014-08-28 17:08:55

今天看到某互联网巨头的面试题,
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
阅读(2593) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~