`
cectsky
  • 浏览: 44751 次
  • 性别: Icon_minigender_1
  • 来自: 哈尔滨
社区版块
存档分类
最新评论

【java】intern方法实践

阅读更多
今天心血来潮,看了看java笔试题,其中有人提到intern的方法,我暂且测试一番。

public static void main(String[] args) {
		String s = new String("abc");
		String b = s.intern();
		if (s == b) {
			System.out.println("字符串abc在常量池中");
		} else {
			System.out.println("字符串abc不在常量池中");
		}

		String s1 = "abc";
		String b1 = s1.intern();
		if (s1 == b1) {
			System.out.println("字符串abc在常量池中");
		} else {
			System.out.println("字符串abc不在常量池中");
		}
	}

结果:
字符串abc不在常量池中
字符串abc在常量池中

详见jdk
public native String intern();

if the pool already contains a string equal to this String object,
then the string from the pool is returned. Otherwise, this String object  is added to the pool and a reference to this String object is returned.
说明b和b1都是来自pool的。而new的Object是动态heap上的,这也从侧面证明了
String s = new String("123");创建几个对象的原理
分享到:
评论
3 楼 fortianwei 2014-05-28  
上面的s之所以 不==b,是因为s是一个存在于堆中的对象,而b是 abc 这个字符串常量,跟s那个对象完全不同,所以不等,试试上,在编译过程中,.class文件中的这个abc字符串已经在常量池中了。
2 楼 Traveling 2014-02-25  
这个文章讲得多一点,可以参考一下
http://blog.sina.com.cn/s/blog_69dcd5ed0101171h.html
1 楼 Traveling 2014-02-25  
String s1 = "abc"; 
String b1 = s1;
结果也一样

相关推荐

Global site tag (gtag.js) - Google Analytics