1比如 String s = new String("silly"); 这个语句产生两个实例,一个是s,一个是"silly".传递给String构造器的的参数("silly")本身就是一个String实例,功能上等于所有北构造器创建的对象.如果这种用法是在一个循环中,或是在一个被频繁调动的方法中,那么成千上万不必要的String实例会被创建.所以不要这样写. 应该 String s = "silly"这样写.
2 String s1 = new String("a"); String s2 = new String("b"); s1 = s2 ; 这样的话s1的值也是b了.
1。当然有区别:前者建立了一个object和两个object reference,后者是建立了一个object和一个object reference。 2。不会。以下是测试 import java.io.*; public class FileTest { public static void main(String args[]) { String a="this is a string"; String b=a; System.out.println(a); System.out.println(b); a=a.substring(3); System.out.println(a); System.out.println(b); } }输出:this is a string this is a string s is a string this is a string
突然记起来,是指向同一个内存地址的,thinking in java说过上面的例子不能做例,因为a=a.substring(3);已经改变了a指向的地址
String s1 = new String("a"); String s2 = new String("b"); s1 = s2 ; 这样的话是将s2引用的内容(即s2指向对象的地址)付给s1.即让s1也指向"b".
首先你要理解constant pool, 这是一个特殊的共享区域,literate, Class这些可以在内存中共享的不经常改变的东西,都可以放在这里。 如果你用了String s = new String("xyz"); 那么,会有两个String被创建,一个是你的Class被CLassLoader加载时,你的"xyz"被作为常量读入,在constant pool里创建了一个共享的"xyz" 然后,当调用到new String("xyz")的时候,会在heap里创建这个new String("xyz"); 但是如果你把String s = new String("xyz").intern(); 那么具体过程变成,现在heap里创建一个String, 然后调用intern()方法,发现constant pool里存在'xyz',然后就会返回constant pool内对象的引用,稍后heap里的就not reachable了,会被gc,最终VM里只有一个"xyz"
String str1 = "str";
会默认建立一个"str"的对象
这个语句产生两个实例,一个是s,一个是"silly".传递给String构造器的的参数("silly")本身就是一个String实例,功能上等于所有北构造器创建的对象.如果这种用法是在一个循环中,或是在一个被频繁调动的方法中,那么成千上万不必要的String实例会被创建.所以不要这样写.
应该 String s = "silly"这样写.
String s2 = new String("b");
s1 = s2 ;
这样的话s1的值也是b了.
2。不会。以下是测试 import java.io.*;
public class FileTest { public static void main(String args[]) {
String a="this is a string";
String b=a;
System.out.println(a);
System.out.println(b); a=a.substring(3); System.out.println(a);
System.out.println(b);
}
}输出:this is a string
this is a string
s is a string
this is a string
String s2 = new String("b");
s1 = s2 ;
这样的话是将s2引用的内容(即s2指向对象的地址)付给s1.即让s1也指向"b".
首先你要理解constant pool, 这是一个特殊的共享区域,literate, Class这些可以在内存中共享的不经常改变的东西,都可以放在这里。
如果你用了String s = new String("xyz");
那么,会有两个String被创建,一个是你的Class被CLassLoader加载时,你的"xyz"被作为常量读入,在constant pool里创建了一个共享的"xyz"
然后,当调用到new String("xyz")的时候,会在heap里创建这个new String("xyz");
但是如果你把String s = new String("xyz").intern();
那么具体过程变成,现在heap里创建一个String, 然后调用intern()方法,发现constant pool里存在'xyz',然后就会返回constant pool内对象的引用,稍后heap里的就not reachable了,会被gc,最终VM里只有一个"xyz"
而后者是一个符值语句,把字符串str符给原有的对象str1
第一个的type是引用
第二个就不是那么简单了 首先创造了2个对象 str 和 "str",再者引用关联了对象 。