JVM的String对象不允许修改 String a =new String("hello") new String("hello")代表生成一个匿名String对象String a =new String("hello")代表新建一个String对象a,并把匿名String对象的值赋给他
如果从便一起的角度,两者存储在内存中的位置是不一样的,一个在heap里,一个在stack里,具体查查书吧。 因为前者实际上是一个常量字符串,不管你定义了多少个String a, String b,这些句柄只是指向同一个常量串 后者每次都新建一个变量,每一个句柄指向一个新的变量(因为忌讳说地址,就不说指向一个新的地址了)
上面的不对 new String("hello")生成String对象前要先生成一个值为"hello"的匿名String对象
做了一个测试: public void test() { String a = "hello"; String b = "hello"; String c = new String("hello"); System.out.println(a.hashCode()); System.out.println(b.hashCode()); System.out.println(c.hashCode()); } 结果是 99162322 99162322 99162322 这是为啥,hashCode和地址有关吗?
两者存储在内存中的位置是不一样的,一个在heap里,一个在stack里, 前者是一个字符串,变量名为a, 在tack里值为hello 后者句柄为a,指向一个String对象,在heap里值为hello 生命周期不同假如比较值是否相等 String a ="hello"; String b ="hello" if(a==b) //比较变量值是否相等 {} String a =new String("hello") String b =new String("hello")if(a==b) //比较句柄值是否相等 {} if(a.equals(b)) // 还可以比较对象内容是否相等 {}
String a ="hello" 创建了一个String对象,JAVA中会对每个字符串常量自动解析成一个String对象. String a =new String("hello")创建了两个String对象,自动解析了一个,用new关键字创建了一个,后面的这个交给a来引用. 试验程序如下: public class TestString {
/** Creates a new instance of TestString */ public TestString() { }
public static void main(String[] args) { // TODO code application logic here int i = 0; String a; while(true) { a = new String("aa" + i++);//1 // a = "aa" + i++; //2 try { Thread.sleep(3000); } catch(Exception e) {} } }
说个effective java里的:
前者只执行一次构造函数
后者每次执行到都会执行一次构造函数
所以,如果在一个次数为n的循环里
前者消耗1
后者消耗n
String a =new String("hello")
new String("hello")代表生成一个匿名String对象String a =new String("hello")代表新建一个String对象a,并把匿名String对象的值赋给他
因为前者实际上是一个常量字符串,不管你定义了多少个String a, String b,这些句柄只是指向同一个常量串
后者每次都新建一个变量,每一个句柄指向一个新的变量(因为忌讳说地址,就不说指向一个新的地址了)
new String("hello")生成String对象前要先生成一个值为"hello"的匿名String对象
public void test()
{
String a = "hello";
String b = "hello";
String c = new String("hello");
System.out.println(a.hashCode());
System.out.println(b.hashCode());
System.out.println(c.hashCode());
}
结果是
99162322
99162322
99162322
这是为啥,hashCode和地址有关吗?
前者是一个字符串,变量名为a, 在tack里值为hello
后者句柄为a,指向一个String对象,在heap里值为hello
生命周期不同假如比较值是否相等
String a ="hello";
String b ="hello"
if(a==b) //比较变量值是否相等
{}
String a =new String("hello")
String b =new String("hello")if(a==b) //比较句柄值是否相等
{}
if(a.equals(b)) // 还可以比较对象内容是否相等
{}
String a =new String("hello")创建了两个String对象,自动解析了一个,用new关键字创建了一个,后面的这个交给a来引用.
试验程序如下:
public class TestString {
/** Creates a new instance of TestString */
public TestString() {
}
public static void main(String[] args) {
// TODO code application logic here
int i = 0;
String a;
while(true)
{
a = new String("aa" + i++);//1
// a = "aa" + i++; //2
try {
Thread.sleep(3000);
} catch(Exception e) {}
}
}
}
这个程序运行后用profiler来查看就可以清楚的看到String对象增长的情况,语句一是一次两个的增长,改用语句二是一次一个的增长.