Fork me on GitHub

特性:

          1.字符串的不可改变性

                        String  s="a"+"b"+"c";

                                   创建了四个对象

                                            在方法常量池中存储   a“,”b“,”c“,三个对象

                                             最后会吧三个拼接到一起在创建一个对象   存储"abc"的对象,a,b,c的对象会被gc在空闲地时候回收

                        体现了字符穿的不可改变型

           2.字符串的底层代码还是字符数组

public String(String original) {
int size = original.count;
char[] originalValue = original.value;
char[] v;
if (originalValue.length > size) {
// The array representing the String is bigger than the new
// String itself. Perhaps this constructor is being called
// in order to trim the baggage, so make a copy of the array.
int off = original.offset;
v = Arrays.copyOfRange(originalValue, off, off+size);
} else {
// The array representing the String is the same
// size as the String, so no point in making a copy.
v = originalValue;
}
this.offset = 0;
this.count = size;
this.value = v;
}

 

两种创建方式

         直接创建   eg:String str="abcd";

         new创建    String s=new String();

存储的位置

          直接存储   字符串会直接存储在方法区中的常量池中

         new 创建     会创建两个对象   首先会创建一个String对象 然后在创建一个字符串对象存储在常量池中,这是堆中存储的是常量池中的地址    常量池中的地址才是字符串真正存储的地址。

 内存图

 

posted on 2017-08-17 23:52  TopTime  阅读(197)  评论(0编辑  收藏  举报