---
title: "三分钟理解Java中字符串（String）的存储和赋值原理"
author: "sameseam"
date: "2010-01-05T13:27:00Z"
tags: []
slug: "java-string"
draft: false
lastmod: "2013-05-06T13:21:17Z"
id: 1860380
url: "https://sameseam.iteye.com/blog/1860380"
---

可能很多java的初学者对String的存储和赋值有迷惑，以下是一个很简单的测试用例，你只需要花几分钟时间便可理解。

1.在看例子之前，确保你理解以下几个术语：

**栈** ：由JVM分配区域，用于保存线程执行的动作和数据引用。栈是一个运行的单位，Java中一个线程就会相应有一个线程栈与之对应。

**堆** ：由JVM分配的，用于存储对象等数据的区域。

**常量池** ：在堆中分配出来的一块存储区域，用于存储**显式** 的String，float或者integer.例如String str="abc"; abc这个字符串是显式声明，所以存储在常量池。

2.看这个例子，用JDK5+junit4.5写的例子，完全通过测试

Java代码 [![复制代码](http://heis.javaeye.com/images/icon_copy.gif)](http://heis.javaeye.com/blog/561472 "复制代码")

01. **import****static**org.junit.Assert.assertNotSame;
02. **import****static**org.junit.Assert.assertSame;
03. **import**org.junit.Test;
04. /\**
05. \*@authorHeis
06. \*
07. \*/
08. **public****class**StringTest{
09. @Test
10. **public****void**testTheSameReference1(){
11. Stringstr1="abc";
12. Stringstr2="abc";
13. Stringstr3="ab"+"c";
14. Stringstr4=**new**String(str2);
15. //str1和str2引用自常量池里的同一个string对象
16. assertSame(str1,str2);
17. //str3通过编译优化，与str1引用自同一个对象
18. assertSame(str1,str3);
19. //str4因为是在堆中重新分配的另一个对象，所以它的引用与str1不同
20. assertNotSame(str1,str4);
21. }
22. }

```
import static org.junit.Assert.assertNotSame;
import static org.junit.Assert.assertSame;

import org.junit.Test;

/**
 * @author Heis
 *
 */
public class StringTest{

	@Test
	public void testTheSameReference1(){
		String str1="abc";
		String str2="abc";
		String str3="ab"+"c";
		String str4=new String(str2);
		
		//str1和str2引用自常量池里的同一个string对象
		assertSame(str1,str2);
		//str3通过编译优化，与str1引用自同一个对象
		assertSame(str1,str3);
		//str4因为是在堆中重新分配的另一个对象，所以它的引用与str1不同
		assertNotSame(str1,str4);
	}
	
}
```

- 第一个断言很好理解，因为在解析的时候，"abc"被存储在常量池中，str1和str2的引用都是指向常量池中的"abc"。**所以str1和str2引用是相同的。**
- 第二个断言是由于编译器做了优化，编译器会先把字符串拼接，再在常量池中查找这个字符串是否存在，如果存在，则让变量直接引用该字符串。**所以str1和str3引用也是相同的。**
- str4的对象不是显式赋值的，编译器会在堆中重新分配一个区域来存储它的对象数据。**所以str1和str4的引用是不一样的。**