Java基础特性
基本数据类型
整形
浮点类型
char
布尔类型
字符串
String 类型可能是 Java 中应用最频繁的引用类型,但它的性能问题却常常被忽略。高效的使用字符串,可以提升系统的整体性能。
String是不可变的,Java 9 后,String 类的实现改用 byte 数组存储字符串,同时使用 coder 来标识使用了哪种编码
点击时的区域标题:点击查看详细内容
public final class String implements java.io.Serializable, Comparable<String>, CharSequence {
/** * The value is used for character storage. * * @implNote This field is trusted by the VM, and is a subject to * constant folding if String instance is constant. Overwriting this * field after construction will cause problems. * * Additionally, it is marked with {@link Stable} to trust the contents * of the array. No other facility in JDK provides this functionality (yet). * {@link Stable} is safe here, because value is never null. */ @Stable private final byte[] value; /** * The identifier of the encoding used to encode the bytes in * {@code value}. The supported values in this implementation are * * LATIN1 * UTF16 * * @implNote This field is trusted by the VM, and is a subject to * constant folding if String instance is constant. Overwriting this * field after construction will cause problems. */ private final byte coder; }
String
不可变的好处?
- 保证 String 对象安全性,避免 String 被篡改。
- 缓存hash,保证hash值不会频繁变更。
- 可以实现字符串常量池。
- String不可变性天生具备线程安全
.substring(n, m)
截取字符串
String.join("", ...)
拼接
在Java7之前,String Pool 被放在运行时常量池中,它属于永久代。而在Java7,String Pool 被移到堆中。这是因为永久代的空间有限,在大量使用字符串的场景下会导致 OutOfMemoryError 错误。
码点、代码单元
String greeting = "🎁 Hello";
int[] codePoints = greeting.codePoints().toArray();
System.out.println(Arrays.toString(codePoints)); // [127873, 32, 72, 101, 108, 108, 111]
String str = new String(codePoints, 0, codePoints.length);
System.out.println(str); // 🎁 Hello
运算符
浮点运算
strictfp
实现严格的浮点计算
数学函数
数组
Arrays.toString(a); // 打印数组
Arrays.copyOf(); // 拷贝数组