String str = new String("abc");
上面语句创建了2个对象,一个"abc"对象是分配在栈中,另一个"abc"对象是new在堆中。String s = new String();
那么这个语句,同样是创建了2个空串么?
另外问下,对于字符串是不是堆内存中有的,栈内存也一定有,换句话说,就是堆内存中的字符串是栈内存中字符串的子集?
上面语句创建了2个对象,一个"abc"对象是分配在栈中,另一个"abc"对象是new在堆中。String s = new String();
那么这个语句,同样是创建了2个空串么?
另外问下,对于字符串是不是堆内存中有的,栈内存也一定有,换句话说,就是堆内存中的字符串是栈内存中字符串的子集?
str 当然引用名也需要有内存地址存储在栈区
个人认为,需要new的都在堆区,不用new的在栈区
String("abc")对象存放在堆中,str引用在栈中。String s = new String();跟String s = new String("")一样,都表示声明一个空的字符串。
String()对象存放在堆中,str引用在栈中;
那关于问题" 堆内存中的字符串是否为栈内存中字符串的子集" 这个问题呢?
有没有哪些例子是创建出来的字符串只存在于堆中,而栈中没有的(当然,我指的是内容一样的字符串)
因为通过String str = new String("abc");这个语句创建堆中字符串时,总是有个"abc"字符串值会先被弄出来,放在栈中?
jvm首先在string常量池内里面查找字符串"abc",
找到,不做任何事情,
否则,创建新的String对象"abc",放到String常量池里面。
然后new,在内存堆(不是string常量池里面)根据常量池的"abc"对象创建string对象存储"abc",并将内存堆上的(不是String常量池内的)String对象返回给str引用。
上面语句创建了2个对象,一个"abc"对象是分配在栈中,另一个"abc"对象是new在堆中。请教一下,这句话正确吗?如何检验在字符串池中有(即栈中)?
/**
* Initializes a newly created {@code String} object so that it represents
* the same sequence of characters as the argument; in other words, the
* newly created string is a copy of the argument string. Unless an
* explicit copy of {@code original} is needed, use of this constructor is
* unnecessary since Strings are immutable.
*
* @param original
* A {@code String}
*/
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;
}
22 // 1 3:dup
23 // 2 4:ldc1 #18 <String "abc">
24 // 3 6:invokespecial #20 <Method void String(String)>
25 // 4 9:astore_1
这条语句在对堆内存中开辟了两个空间,因为"abc"本来就是String类得匿名对象,它在堆内存中就已经占据了一个空间,现在又使用new 开辟了一个新的堆内存空间 , 使得str的引用指向新开辟的堆内存空间