字符串
String
核心要点
String符串是引用类型,本身就是一个类。由于String比较常用,Java编译时对其进行特殊处理,可以用 “xxx”的方式创建对象;
String str = "1234";String对象实际存储的是char[], 实际写法如下;
String n = new String(new char[] {'h', 'e', 'l', 'l', 'o'});-
Java中字符串是 不可变的,String内部通过private final char value[];存储。/* * @author zd * @date 2025/8/9 * @apiNote String类-常见用法 */ public class DemoString { public static void main(String[] args) { String s1 = "hello"; System.out.println(s1);//hello System.out.println(s1.hashCode());//99162322 s1 = s1.toUpperCase(); System.out.println(s1);//HELLO System.out.println(s1.hashCode());//68624562 } }注释: 上述代码中,对字符串
s1进行操作,对象的值发生了改变,但对象的hash值不同。引用类型对象值相等前提是 值相等且hash地址相同,所以说明s1字符串为发生改变,只是改变了对象的地址。
常用方法
| 方法描述 | 方法声明 |
|---|---|
| 字符串比较 | public boolean equals(Object anObject); |
| 字符串首位去空格 | public String trim(); |
| 替换子串 | public String replace(CharSequence target, CharSequence replacement); |
| 分割子串 | public String[] split(String regex); |
| 拼接子串 | public static String join(CharSequence delimiter, CharSequence… elements); |
| 格式化字符串 | public static String format(String format, Object… args); |
| 数据类型转换 | public static String valueOf(int i); |
| 转换为char[] | public char[] toCharArray(); |
| 包含子串 | public boolean contains(CharSequence s); |
| 截取子串 | public String substring(int beginIndex); |
| 拼接字符串 | public String concat(String str); |
代码示例
/*
* @author zd
* @date 2025/8/9
* @apiNote String类-常见方法
*/
public class DemoString {
public static void main(String[] args) {
//字符串比较
String s1 = "hello";
String s2 = "hello";
System.out.println(s1 == s2);
System.out.println(s1.equals(s2));
//首尾去空格
String s3 = " hello ";
System.out.println(s3.trim());
//替换子串
String s4 = "hello world";
System.out.println(s4.replace("world", "java"));
//分割子串
String s5 = "hello,world,java";
System.out.println(s5.split(","));
//拼接子串
String s6 = "hello";
String s7 = "world";
System.out.println(String.join(s6, s7));
System.out.println(String.join("-",s6, s7));
//格式化字符串
System.out.println(String.format("Hi %s, your score is %.2f!", "Bob", 59.5));
//数据类型转换
String.valueOf(12);
//字符串转换字符数组
String s8 = "hello";
char[] chars = s8.toCharArray();
for (char c : chars) {
System.out.println(c);
}
}
}注意
-
**字符串比较:**在
java中对两个引用类型进行比较必须使用equals方法进行。在进行字符串比较的时候虽然==也可以进行比较,因为String作为常量存储在JVM常量池中。要忽略大小写进行比较需要使用equalsIgnoreCase方法。 -
**字符串首位去空格:**字符串是不可变的,所以没有修改字符串而是返回一个新的字符串,空白字符包括空格,
\t,\r,\n;
StringBuilder/StringBuffer
进阶
JAVA中对字符串拼接也做了特殊处理,可以通过+对多个字符串进行拼接。String a = "a"+"b"; 此类普通的拼接在编译环节,虚拟机会将操作优化为”ab”。
String str1 = "hello";
String str2 = str1 + "world";当拼接操作为上述方式时,会导致创建多个String对象,造成资源浪费影响GC效率。如果需要优化此类操作,则需使用StringBuilder、StringBuffer类进行拼接字符串拼接。
核心要点
StringBuilder是一个可变对象,通过预分配缓冲区的方式解决多次创建丢弃对象拼接字符串的作用。
常用方法
| 方法描述 | 方法声明 |
|---|---|
| 字符串拼接 | public StringBuilder append(String str); |
| 字符串插入 | public StringBuilder insert(int offset, String str); |
| 字符串删除 | public StringBuilder delete(int start, int end); |
| 子串替换 | public StringBuilder replace(int start, int end, String str); |
| 字符串反转 | public StringBuilder reverse(); |
代码示例
public class DemoStringBuilder {
public static void main(String[] args) {
//拼接
StringBuilder sb = new StringBuilder("hello");
sb.append(" ").append("world");
System.out.println(sb);//hello world
//插入
sb.insert(5, " java");
System.out.println(sb);//hello java world
//删除
sb.delete(5, 10);
System.out.println(sb);//hello world
//替换
sb.replace(6, 12, "java");
System.out.println(sb);//hello java
//反转
sb.reverse();
System.out.println(sb);//avaj olleh
}
}注意
StringBuilder | StringBuffer | |
|---|---|---|
| 线程安全 | ❌ 非线程安全(性能更高) | ✅ 线程安全(方法用 synchronized 修饰) |
| 适用场景 | 单线程环境 | 多线程环境(如全局变量、共享资源) |
| 性能差异 | 更快 | 稍慢,内部有synchronized锁同步机制 |
- 都继承自
AbstractStringBuilder抽象类,内部方法相同; - 可以直接修改内部
char[]解决了String不可修改的功能; - 默认 16 字符,可预设容量减少扩容次数。
建议:优先使用StringBuilder 而 StringBuffer是历史遗留类。
包装类
概述
Java中已知数据类型有两大类:
基本类型:byte、short、int、long、boolean、float、double、char;
**引用类型:**所有的class、interface类型。
引用类型可以赋值为null,而基本类型不可以。如果需要将基本类型转换为引用类型需要创建一个只有基本类型属性的类:
/*
* @author zd
* @date 2025/8/10
* @apiNote 模拟引用类型int
*/
public class DemoInteger {
private int value;
public DemoInteger(int value) {
this.value = value;
}
public int getValue() {
return value;
}
}
//使用
DemoInteger i = new DemoInteger(10);//基本类型转换为引用类型
int value1 = i.getValue();//引用类型转换为基本类型由于基本类型的引用类型较为常用,Java中已提供了这些封装类:
| 基本类型 | 对应的引用类型 |
|---|---|
| boolean | java.lang.Boolean |
| byte | java.lang.Byte |
| short | java.lang.Short |
| int | java.lang.Integer |
| long | java.lang.Long |
| float | java.lang.Float |
| double | java.lang.Double |
| char | java.lang.Character |
装箱和拆箱
**自动装箱及拆箱:**jdk1.5引入了自动装箱及拆箱,编译器会自动在基本类型和引用类型进行转换的时候进行处理,无需再进行调用valueOf等方案进行转换。
//自动装箱
int value2 = 10;
Integer i2 = value2;
List<Integer> numbers = new ArrayList<>();
numbers.add(100);
//自动拆箱
Integer i3 = new Integer(100);
int value3 = i3;注意
- 装箱和封箱是一种”语法糖”,只是再编写代码的过程中省略了方法调用转换类型,实际在编译后文件中还是存在方法调用的;
- 自动拆箱如果初始化对象为null,会遇到空指针异常;
- 包装类对象对比使用
equals方法。
枚举类
用
enum修饰的类,用于定义一组常量。
简单使用
// 定义一个简单的枚举类
public enum Season {
SPRING, SUMMER, AUTUMN, WINTER
}有属性的枚举
public enum Planet {
// 枚举常量后面的括号实际上是调用构造函数
MERCURY(3.303e+23, 2.4397e6),
VENUS(4.869e+24, 6.0518e6),
EARTH(5.976e+24, 6.37814e6),
MARS(6.421e+23, 3.3972e6),
JUPITER(1.9e+27, 7.1492e7),
SATURN(5.688e+26, 6.0268e7),
URANUS(8.686e+25, 2.5559e7),
NEPTUNE(1.024e+26, 2.4746e7);
// 枚举类的字段
private final double mass; // in kilograms
private final double radius; // in meters
// 枚举类的构造函数(默认为private)
Planet(double mass, double radius) {
this.mass = mass;
this.radius = radius;
}
// 枚举类的方法
public double surfaceGravity() {
return 6.67300E-11 * mass / (radius * radius);
}
public double surfaceWeight(double otherMass) {
return otherMass * surfaceGravity();
}
}BigDecimal
一个任意大小且精度完全准确的浮点数。
常用方法
| 方法描述 | 方法声明 |
|---|---|
| 构造方法,类型转换 | public BigDecimal(String val); |
| 比较 | public int compareTo(BigDecimal val); |
| 相加 | public BigDecimal add(BigDecimal augend); |
| 相减 | public BigDecimal subtract(BigDecimal subtrahend); |
| 相乘 | public BigDecimal multiply(BigDecimal multiplicand) ; |
| 相除 | public BigDecimal divide(BigDecimal divisor); |
| 设置精度 | public BigDecimal setScale(int newScale, int roundingMode); |