1. String s = new String("abc");
在编译期,根据“abc”创建一个对象,存放到string pool中,这时需要查看string pool中是否已经有了“abc”,若已有则不创建,若无则创建。
在运行期,根据new创建一个对象,存放到heap中。即将pool中的对象复制一份到heap中,并把heap中的这个对象引用交给s持有。
综上,该语句创建一个或两个对象。 导致在heap中出现内容相同而地址不同的String对象。
2. String s1 = "abc";
在编译期,根据“abc”创建一个对象,存放到string pool中,这时需要查看string pool中是否已经有了“abc”,若已有则不创建,若无则创建。
3. ==是比较地址,equals是比较内容 。
4. intern()方法:查找内容相同的字符串,如:
String s2 = "hello";//hello不存在,创建新对象存在string pool中(1) String s2 = new String("hello");//创建新对象存在heap中 s1 == s2;//false 地址不同 s1.equals(s2);//true 内容相同 s2 = s2.intern();//查找与s2内容相同的对象,并赋给s2 s1 == s2;//true 此时s1,s2同指向(1)
5. java中所有的字符串文字都是一个String对象
6. String是不可变类,线程安全,不存在任何修改对象的方法
7. StringBuffer是可变类,用来修改对象
StringBuffer D = new StringBuffer("ss");//创建两个对象
D.append("test");//在new对象上直接处理,不产生新的对象
实例
public class StringChar {
public static void main(String[] args){
String s = "hello";//(1)存放在Constant pool里的String pool里
String s2 = new String("hello");//(2)new出来的对象存放在heap里
String t = "hello";//(3)因为string pool里已经有了hello,所以t与s指向同一内存地址
String str = "hello";//(4)同上
char c[] = {'h','e','l','l','o'};
char ch[] = str.toCharArray();//string转换为char
if(ch == c){
System.out.println("true");
}else{
System.out.println("flase");
}//false
if(ch.equals(c)){
System.out.println("true");
}else{
System.out.println("flase");
}//false why???
if(s2 == s){//"=="判断引用是否相同,即是否指向同一内存地址
System.out.println("true");
}else{
System.out.println("flase");
}//false
if(s2.equals(s)){//equals()判断两个object是否一样,即所有的成员值都相同
System.out.println("true");
}else{
System.out.println("flase");
}//true
s2 = s2.intern();//intern()找到与s2内容相同的对象,并将其赋给s2
System.out.println(s == s2);//true 此时s2和s指向同一对象(1)
System.out.println(t == s2);//true 因为t和s指向同一对象(1),所以此时t和s2指向同一对象(1)
System.out.println(str == s2);//true 同上
}
}