介绍
The String class represents character strings. All string literals in Java programs, such as "abc", are implemented as instances of this class. Strings are constant, their values cannot be changed after they are created.
示例
public class Test {
public static void main(String[] args) {
char data[] = {'a', 'b', 'c'};
String str = new String(data);
System.out.println(str);
}
}
结构
源码
成员变量
/** The value is used for character storage. */
private final char value[];
构造方法
/**
* Allocates a new {String} so that it represents the sequence of
* characters currently contained in the character array argument.
*/
public String(char value[]) {
this.value = Arrays.copyOf(value, value.length);
}
成员方法
/**
* Returns the length of this string.
*/
public int length() {
return value.length;
}
面试题
Java9 后 String 为什么使用 byte[] 而不是 char[] ?
因为 JDK 开发人员发现人们使用的字符串的值是拉丁字符居多,而之前使用的 char 数组,每一个 char 占用两个字节而拉丁字符只需要一个字节就可以存储,剩下的一个字节就浪费了,造成内存的浪费,gc 的更加频繁。