String相关的类
1.String不可变的类
源码:
public final class Stringimplements 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;
}
final char[] value; ---- 常量数组不可变
2.StringBuffer和StringBuilder
可变的类,线程安全,效率低,方法基本都加上了synchronized
源码:
abstract sealed class AbstractStringBuilder{char[] value; ---- 可变数组}public final class StringBuffer extends AbstractStringBuilder{public synchronized StringBuffer append(Object obj) {toStringCache = null;super.append(String.valueOf(obj));return this;}}
StringBuilder:可变的类,线程不安全,效率高,StringBuffer 一样的,但是方法没有加上synchronized
3.面试知识点
面试题一:
常量池中的数据是唯一的
//面试题一:以下代码创建几个对象//答案:一个 (常量池中的数据是唯一的)String str1 = "hello";String str2 = "hello";System.out.println(str1 == str2); //true
面试题二:
//面试题二:以下代码创建几个对象//答案:三个 (堆内存中创建了两个对象,常量池中创建了一个对象)String str3 = new String("hello");String str4 = new String("hello");System.out.println(str3 == str4); //false
面试题三:
//面试题三:String的拼接问题 常量在编译时直接拼接String str5 = "he" + "llo"; //相当于 String str5 = "hello";System.out.println(str5 == str1); //true
面试题四:
//面试题四:String的拼接问题 常量在编译时直接拼接final String str6 = "he";final String str7 = "llo";String str8 = str6 + str7; //相当于 String str8 = "hello";System.out.println(str8 == str1); //true
面试题五:
//面试题五:String的拼接存在变量时,底层创建StringBuilder对象拼接String str9 = "he";String str10 = "llo";String str11 = str9 + str10; //相当于 String str11 = new StringBuilder(String.valueof(str9)).append(str10).toString();System.out.println(str11 == str1); //false
总结:
字符串常量与常量拼接,会去在常量池里面找有没有,如果没有常量池创建对象。
正则表达式
含义:用来描述或者匹配一系列符合某个语句规格的字符串