String类
首先对于String类型,我们先查看它的源码:
public final class String
implements java.io.Serializable, Comparable<String>, CharSequence {
/** The value is used for character storage. */
private final char value[];
/** Cache the hash code for the string */
private int hash; // Default to 0
/** use serialVersionUID from JDK 1.0.2 for interoperability */
private static final long serialVersionUID = -6849794470754667710L;
由此我们可以知道,String类型内部维护的char[]数组,且其是由final修饰的,可知一旦创建就不能在修改。
1.在创建字符串S后,Java运行时会拿着这个S字符串在字符串常量池中查找是否存在内容相同的字符串对象,如果不存在,则在池中创建一个字符串S,否则不会创建对象,也不会在池中添加。
2.使用new关键创建对象,那么肯定会在堆栈创建一个新的对象,String也是一样的。
3.使用直接指定或者使用纯字符串拼接来创建String对象,则仅仅会检查String池中的字符串,池中没有就创建一个,如果存在,就不需要创建新的,但是绝对不会在堆栈区再去创建对象。
4.使用包含变量的表达式来创建String对象时,则不仅会检查并维护字符串常量池,而且还会在堆栈区创建一个新的String对象
字符串拼接
1.利用"+"
public class TestDemo {
public static void main(String[] args) {
String str1="hello ";
String str2="world";
String str3=str1+str2;
System.out.println(str3);
}
}
2.利用concat
public class TestDemo {
public static void main(String[] args) {
String str1="hello ";
String str2="world";
String str3=str1.concat(str2);
System.out.println(str3);
}
}
3.利用StringBuffer
public class TestDemo {
public static void main(String[] args) {
StringBuffer str3=new StringBuffer("hello");
str3.append(" ").append("world");
System.out.println(str3);
}
}
总结:若拼接三个以上的字符串,为避免临时字符串的产生可以选择StringBuffer,若拼接三个以上的字符串,只选择一行语句代码,选择"+",效率最高,选择concat。
字符串比较
在比较字符串内容是否相同时,要使用equals比较,不能使用"=="比较。
public class TestDemo {
public static void main(String[] args) {
String str1="hello";
String str2="hello";
System.out.println(str1==str2);
System.out.println(str1.equals(str2));
}
}
输出结果:
因为在创建str2时,会再字符串常量池中查找是否有和str2内容相同的字符串,因为在字符串常量池中已经创建了str1=hello,故str1和str2所占内存地址也是相同的,内容也相同,故而输出均为true。
public class TestDemo {
public static void main(String[] args) {
String str1="hello";
String str2=new String("hello");
System.out.println(str1==str2);
System.out.println(str1.equals(str2));
}
}
输出结果:
此时,str2则是被new出来了,则需要为其开辟新的内存空间,故而第一个输出为false,equals比较的是字符串的内容。
因此,在比较字符串内容时应该使用的是equals。