Skip to main content

常用类

包装类

包装类概念

包装类把基本数据类型转换为对象。

  • 每个基本类型在java.lang包中都有一个相应的包装类。

包装类的作用

  • 提供了一系列实用的方法。
  • 集合不允许存放基本数据类型数据,存放数字时,要用包装类。

image-20250709171540168

byte short int long float double 他们的包装类分别是 首字母大写对应的包装类名称,int的包装类是全称。

Byte Short Integer Long Float Double 他们分别的父类都是Number包装类。

boolean char 数据类型他们的包装类 分别是 Boolean和Character包装类。

Boolean类和Number类,Character类他们的父类都是 Object类。

穿了一个马甲,基本数据类型变为了对象形式。

包装类构造方法

每一个包装类的构造方法都有两个构造方法,除了Character类之外。

1、所有包装类都可将与之对应的基本数据类型作为参数,来构造它们的实例,例如:public Type (type value)。

2、除了 Character 类外,其他包装类可将一个字符串作为参数构造他们的实例,例如:public Type (String value)。

3、使用字符串构造 Number子类(Byte Short Integer Long Float Double)实例,字符串不能为 null,并且必须可以解析为正确的数值才可以,否则将报 NumberFormatException异常,中断程序。

例如:
Integer i = new Integer(1);

Integer i = new Integer("123")

使用包装类构造方法创建实例案例:

package com.baoZhuangPart.Test01;

/**
* 数据类型: byte short int long float double boolean char
* 对应的包装类:Byte Short Integer Long Float Double Boolean Character
*
* 包装类构造方法:
* 所有包装类都可将与之对应的基本数据类型作为参数,来构造它们的实例
* 除Character类外,其他包装类可将一个字符串作为参数构造它们的实例
*
* 使用字符串构造Number子类实例,字符串不能为null,并且必须可以解析为正确的数值才可以,否则将报NumberFormatException
*/

public class TestConstructor {
public static void main(String[] args) {
// 默认一个 整数是 int 类型 需要强制转为 byte类型
Byte b1 = new Byte((byte)120); // 使用基本数据类型来创建对象
System.out.println("b1 = " + b1);

byte b = 110;
Byte b2 = new Byte(b); // 所有包装类都可将与之对应的基本数据类型作为参数,来构造它们的实例
System.out.println("b2 = " + b2);

Byte b3 = new Byte("11"); // 除Character类外,其他包装类可将一个字符串作为参数构造它们的实例
System.out.println("b3 = " + b3);

System.out.println("------------------------------------");

Short s1 = new Short((short)345);
System.out.println("s1 = " + s1);

Short s2 = new Short("234");
System.out.println("s2 = " + s2);

System.out.println("------------------------------------");

Integer i1 = new Integer(1234);
System.out.println("i1 = " + i1);

Integer i2 = new Integer("3456");
System.out.println("i2 = " + i2);

System.out.println("------------------------------------");

Long l1 = new Long(4657);
System.out.println("l1 = " + l1);

Long l2 = new Long("7829092");
System.out.println("l2 = " + l2);

System.out.println("------------------------------------");

Boolean bl1 = new Boolean(true);
System.out.println("bl1 = " + bl1);

Boolean bl2 = new Boolean(false);
System.out.println("bl2 = " + bl2);

// 使用字符串构造Boolean实例 不区分大小写 如果内容为true 则表示为true
// 其他的任何字符串都表示为false 包括null
Boolean bl3 = new Boolean(null);
System.out.println("bl3 = " + bl3); // false
Boolean bl4 = new Boolean("true");
System.out.println("bl4 = " + bl4); // true

System.out.println("------------------------------------");
Character ch1 = new Character('a');
System.out.println("ch1 = " + ch1);

}

}

包装类的常用方法

xxxValue()

每一个包装类,都提供有xxxValue(),用于将包装类对象,转换为基本数据类型。

xxxValue()有:byteValue(),intValue(),charValue(),longValue(),shortValue(),doubleValue(),floatValue(),booleanValue()。

作用:每一个包装类,都提供有xxxValue(),用于将包装类对象,转换为基本数据类型,此方法为实例方法。

参数:包装类对象

返回值:基本数据类型

示例:
Byte b2 = new Byte((byte)123) // 包装类对象
Byte b1 = new Byte("123"); // 包装类对象
byte b = b1.byteValue(); // 基本数据类型
byte b3 = b2.byteValue(); // 基本数据类型

包装类方法的使用示例

// 包装类对象一个存在于堆中,基本数据类型一个存在于栈中。

package com.baoZhuangPart.Test01;

/**
*
* 包装对象 -> 基本数据类型
* 每个包装类都提供有xxxValue()方法,用于将包装类对象,转换为基本数据类型,此方法为实例方法
*/

public class TestXXXValue {
public static void main(String[] args) {
// 包装类对象
Byte b1 = new Byte("123");
// 使用 byteValue() 转为基本数据类型
byte b = b1.byteValue();
System.out.println("b = " + b);
Short s1 = new Short("123");
short i = s1.shortValue();
System.out.println("i = " + i);

System.out.println("-------------------------------");

Integer i1 = new Integer("123");
int i2 = i1.intValue();
System.out.println("i2 = " + i2);

System.out.println("-------------------------------");


Long l1 = new Long("11234");
long l = l1.longValue();
System.out.println("l = " + l);

System.out.println("-------------------------------");

Boolean bl1 = new Boolean(true);
boolean b2 = bl1.booleanValue();
System.out.println("b2 = " + b2);

System.out.println("-------------------------------");

Character ch1 = new Character('a');
char c = ch1.charValue();
System.out.println("c = " + c);
}
}

valueOf()

作用:每个包装类都提供有valueof方法,用于将基本数据类型转为包装类对象,此方法为静态方法。

参数:基本数据类型

返回值:包装类对象

示例:
Byte byte = Byte.valueOf((byte)11)
Short short = Short.valueOf((short)11)

valueOf使用示例

package com.baoZhuangPart.Test01;
/**
*
* 基本数据类型 -> 包装对象
* 每个包装类都提供有valueOf方法 用于将基本数据类型转换为包装类对象 此方法为静态方法
* static valueOf()
*
*/
public class TestValueOf {
public static void main(String[] args) {
// 基本数据类型 11 转为包装类对象
Byte aByte = Byte.valueOf((byte) 11);
System.out.println("aByte = " + aByte);
System.out.println("---------------------------------");
Short aShort = Short.valueOf((short) 11);
System.out.println("aShort = " + aShort);
System.out.println("---------------------------------");
Integer integer = Integer.valueOf(123);
System.out.println("integer = " + integer);
System.out.println("---------------------------------");
Long aLong = Long.valueOf(12344);
System.out.println("aLong = " + aLong);
System.out.println("---------------------------------");
Boolean aBoolean = Boolean.valueOf(true);
System.out.println("aBoolean = " + aBoolean);
System.out.println("---------------------------------");
Character character = Character.valueOf('a');
System.out.println("character = " + character);
}
}

toString()

作用:以字符串形式返回包装对象表示的基本数据类型(基本类型 -> 字符串),此方法(带参数)是静态方法。

参数:基本数据类型

返回值:包装类对象

示例:
String sex = Character.toString('男'); // 将基本char数据类型 '男' 转为字符串。
String id = Integer.toString(25); // 将基本int类型数据 25 转为字符串

注意:

包装类中的toString()方法和Object类中的toString()方法,不是同一个,没有继承关系。(参数不一样)

包装类的toString方法是静态方法,Object类中的toString方法是实例方法。

Object类中的toString可以重写,返回值类型,参数,访问权限都得一样。

包装类中的toString方法是静态方法,不可以被重写。

包装类中toString方法示例:

package com.baoZhuangPart.Test01;

/**
* toString():以字符串形式返回包装对象表示的基本类型数据(基本类型->字符串)
*/

public class TestToString {
public static void main(String[] args) {
// 将基本数据类型转为字符串
String s1 = Byte.toString((byte) 123);
System.out.println("s1 = " + s1);
String s2 = Short.toString((short) 1234);
System.out.println("s2 = " + s2);

String s3 = Integer.toString(123);
System.out.println("s3 = " + s3);

String s4 = Long.toString(123);
System.out.println("s4 = " + s4);

String s5 = Boolean.toString(true);
System.out.println("s5 = " + s5);

String s6 = Float.toString(3.5F);
System.out.println("s6 = " + s6);

String s7 = Double.toString(2.2);
System.out.println("s7 = " + s7);

String s8 = Character.toString('A');
System.out.println("s8 = " + s8);
}
}

parseXXX()

parseXXX()有:
xxxValue()有:parseByte(),parseInt(),parseChar(),parseLong(),parseShort(),parseDouble(),parseFloatValue(),parseBoolean()。
作用:每个包装类都提供有parseXxx方法,用于将字符串转换为基本数据类型,此方法为静态方法。

参数:字符串

返回值:基本数据类型

示例:
// 字符串转为byte
byte b = Byte.parseByte("123");

// 字符串为 “true"时,才为true,其他都为false。
boolean b = Boolean.parseBoolean("true")

包装类的parseXXX()方法示例

package com.baoZhuangPart.Test01;

/**
* parseXXX : 每个包装类都提供有parseXXX方法 用于将字符串转化为基本数据类型 此方法为静态方法
*/

public class TestParseXXX {
public static void main(String[] args) {
byte b = Byte.parseByte("123");
System.out.println("b = " + b);

short i = Short.parseShort("123");
System.out.println("i = " + i);

int i1 = Integer.parseInt("123");
System.out.println("i1 = " + i1);

long l = Long.parseLong("1234");
System.out.println("l = " + l);


float v = Float.parseFloat("3.5F");
System.out.println("v = " + v);

double v1 = Double.parseDouble("123");
System.out.println("v1 = " + v1);

// 转换规则和Boolean包装类使用字符串构造实例相同
boolean abc = Boolean.parseBoolean("abc");
System.out.println("abc = " + abc);
}
}

自动装箱和拆箱

基本数据类型和包装类对象的自动转换(jdk1.5之后),允许包装类对象和基本数据类型混合使用计算。

装箱:基本数据类型转换为包装类对象

拆箱:包装类对象转为基本数据类型的值

示例:

Integer intObject = 5; // 自动装箱
int intValue = intObject; // 自动拆箱

背景:

// 例如 要实现 a+c,就需要先转为 byte类型后才能相加。
Byte a = new Byte("123");
byte b = a.byteValue();
byte c = 1;
System.out.println(b + c)

// 在jdk1.5之后就可以直接进行相加,自动装箱和拆箱
Short s1 = 1;
Short s2 = new Short("123"); // 自动拆箱为基本数据类型。
System.out.println(s1 + s2)

自动装箱和拆箱原理

自动装箱:底层自动调用了 valueOf(100) // valueOf(100) 方法

自动装箱和拆箱示例:

package com.baoZhuangPart.Test01;

public class TestAutoConvert {
public static void main(String[] args) {
Integer i1 = 100; // 底层相当于调用了 valueOf(100);基本数据类型转为包装类对象
int number = i1; // 底层相当于调用了 intValue() 包装类对象转为基本数据类型
System.out.println("-----------------------------------");
Byte a = new Byte("123"); // 装箱
byte b = a.byteValue(); // 拆箱
byte c = 1;
System.out.println(b + c);
System.out.println("-----------------------------------");
Short s1 = new Short("123");
short s2 = 123;
System.out.println(s1 + s2);
}
}

包装类相关面试题目

package com.baoZhuangPart.Test01;

public class TestInterview {
public static void main(String[] args) {

Integer a = 127;
Integer b = 127;
System.out.println(a == b); // true

Integer c = -129;
Integer d = -129;

System.out.println(c == d); // false


Integer e = new Integer(-128);
Integer f = new Integer(-128);
System.out.println(e == f); // false 只要是new的 地址永远都不相同

Short s1 = 200;
Short s2 = 200;
System.out.println(s1 == s2); // false


Short s3 = 100;
Short s4 = 100;
System.out.println(s3 == s4); // true

Long l1 = 100L;
Long l2 = 100L;
System.out.println(l1 == l2); // true

Long l3 = 128L;
Long l4 = 128L;
System.out.println(l3 == l4); // false

Character ch1 = 28;
Character ch2 = 28;
System.out.println(ch1 == ch2); // true
}
}

回顾==和equals的区别?

Short Integer Long Character 包装类相关面试题回答:

这四个包装类,直接使用等号赋值的方式创建对象,如果在byte取值范围以内,则从缓存数组中取出对应的元素。

多次取出相同数值的为 同一个元素 所以地址相同。

如果不在byte取值范围以内,则直接new新的对象,所以地址不同。

包装类存储的底层源码分析:源码Integer.java( 任意一种类型的包装类查看),搜索valueOf。

    private static class IntegerCache {
static final int low = -128;
static final int high;
static final Integer cache[];

static {
// high value may be configured by property
int h = 127;
String integerCacheHighPropValue =
sun.misc.VM.getSavedProperty("java.lang.Integer.IntegerCache.high");
if (integerCacheHighPropValue != null) {
try {
int i = parseInt(integerCacheHighPropValue);
i = Math.max(i, 127);
// Maximum array size is Integer.MAX_VALUE
h = Math.min(i, Integer.MAX_VALUE - (-low) -1);
} catch( NumberFormatException nfe) {
// If the property cannot be parsed into an int, ignore it.
}
}
high = h;

cache = new Integer[(high - low) + 1];
int j = low;
for(int k = 0; k < cache.length; k++)
cache[k] = new Integer(j++);

// range [-128, 127] must be interned (JLS7 5.1.7)
assert IntegerCache.high >= 127;
}

private IntegerCache() {}
}

/**
* Returns an {@code Integer} instance representing the specified
* {@code int} value. If a new {@code Integer} instance is not
* required, this method should generally be used in preference to
* the constructor {@link #Integer(int)}, as this method is likely
* to yield significantly better space and time performance by
* caching frequently requested values.
*
* This method will always cache values in the range -128 to 127,
* inclusive, and may cache other values outside of this range.
*
* @param i an {@code int} value.
* @return an {@code Integer} instance representing {@code i}.
* @since 1.5
*/
public static Integer valueOf(int i) {
if (i >= IntegerCache.low && i <= IntegerCache.high)
return IntegerCache.cache[i + (-IntegerCache.low)];
return new Integer(i);
}

总结:integer,Short,Long,Character这四个包装类,直接使用等号赋值的方式创建对象,如果在byte取值范围以内,则从缓存数组中取出对应的元素,多次取出相同数组的为同一个元素,这个范围通过JVM参数是可以调整的,默认是byte范围。如果不在byte取值范围以内,则直接new新的对象,地址不同。

Math类

Math类 数学工具类 提供了常用的数学计算的方法。

abs() 绝对值

System.out.println(Math.abs(-123)); // 123

ceil() 向上取整

System.out.println(Math.ceil(3.3)); // 4.0

floor() 向下取整

System.out.println(Math.floor(3.6)); // 3.0

round() 四舍五入

System.out.println(Math.round(3.5)); // 4

max() 求最大值

System.out.println(Math.max(23, 33)); // 33

min() 求最小值

System.out.println(Math.min(23, 33)); // 23

random() 获取随机数

double random = Math.random();
System.out.println("random = " + random); // random = 0.03458259959718768
System.out.println((int)(random * 100)); // 3

System.out.println((int)(random * 12)); // 12以内随机数

常量

System.out.println(Math.E); // 2.718281828459045
System.out.println(Math.PI); // 3.141592653589793

Random类

Random 专门用于生成随机数据的类

nextBoolean()

作用:生成一个随机布尔值;实例方法

参数:无

返回值:布尔

示例:
Random random = new Random();
random.nextBoolean();

nextInt()

作用:生成一个随机 int值;实例方法

参数:无或一个int数值

返回值:int数值

示例:
Random random = new Random();
random.nextInt(100) // 100 以内数值
random.nextInt() // int类型随机数

nextFloat()

作用:生成一个随机浮点值;实例方法

参数:无

返回值:浮点值

示例:
Random random = new Random();
random.nextFloat();

nextDouble()

作用:生成一个随机double值;实例方法

参数:无

返回值:double值

示例:
Random random = new Random();
random.nextDouble();

System类

System类 系统类 提供了用于获取系统信息的各种方法。System类的构造方法是私有修饰的,不能够new 对象。

currentTimeMillis()

作用:获取当前系统时间,单位为毫秒,从1970年1月1日0点0分0秒到目前,时间戳。

参数:无

返回值:long类型

示例:
// currentTimeMillis()
long currentTimeMillis = System.currentTimeMillis();
System.out.println("currentTimeMillis = " + currentTimeMillis);

nanoTime()

作用:获取当前系统时间,单位为纳秒,从1970年1月1日0点0分0秒到目前,时间戳。

参数:无

返回值:long类型

示例:
long l = System.nanoTime();
System.out.println("l = " + l);

arraycopy(Object src, int srcPos, Object dest, int destPos, int length)

作用:将源数组的一部分内容复制到目标数组的指定位置上

参数:见下

返回值:无

示例:
public class ArrayCopyDemo {
public static void main(String[] args) {
int[] src = {1, 2, 3, 4, 5};
int[] dest = new int[5];

// 从src[1]开始,复制3个元素到dest[0]
System.arraycopy(src, 1, dest, 0, 3);

// 打印结果
for (int i : dest) {
System.out.print(i + " ");
}
// 输出:2 3 4 0 0
}
}


参数说明
src原始数组(源数组)
srcPos源数组中开始复制的起始位置(索引)
dest目标数组(目标数组)
destPos目标数组中复制开始的位置(索引)
length要复制的元素个数

注意:

  • srcdest 必须是相同类型或兼容的数组类型。
  • 如果索引越界或数组类型不匹配,会抛出运行时异常,

示例2:拷贝同一个数组

public class ArrayCopyShift {
public static void main(String[] args) {
int[] array = {1, 2, 3, 4, 5};

// 将 array[2..4] 移动到 array[3..5]
System.arraycopy(array, 2, array, 3, 2);

// 输出结果
for (int i : array) {
System.out.print(i + " ");
}
// 输出:1 2 3 3 4
}
}

clearProperty(String key)

作用:用于从 Properties 对象中删除指定键及其对应的值,通常用于清除配置项。

参数:String类型值

返回值:被移除的键所对应的值(Object 类型),如果键不存在则返回 null。

示例:
import java.util.Properties;

public class ClearPropertyDemo {
public static void main(String[] args) {
Properties props = new Properties();

// 添加属性
props.setProperty("username", "admin");
props.setProperty("password", "123456");

// 输出原始属性
System.out.println("Before clear: " + props);

// 移除 password 属性
Object removedValue = props.clearProperty("password");

// 输出移除结果
System.out.println("Removed value: " + removedValue); // 输出: 123456

// 输出修改后的属性
System.out.println("After clear: " + props);
}
}

使用场景:

清除某个配置项(如用户注销清除 token、缓存失效移除配置等)。
操作.properties配置文件时,有选择地移除某些属性。

exit(int status)

作用:退出JVM虚拟机

参数:-1:正常退出,其他均为强制退出。

返回值:无

示例:
// 退出虚拟机,后边的代码不会再执行
System.exit(1);

gc()

作用:运行垃圾回收器,底层调用的是Runtime类实例方法gc().

参数:无

返回值:无

示例:
// 运行垃圾回收器,回收可以被回收的对象
System.gc();

// 垃圾回收器可以回收哪些对象:
当当前对象没有任何引用指向时,这个对象就会被回收
例如:
Student stu = new Student();
stu = null; // 从栈的角度,这个stu引用就不会指向堆的空间
// 从堆的角度,没有引用指向它了,所以 new Student的这个对象,就访问不到了。
// 所以运行垃圾回收器,就会回收这样的对象

// 如何判断哪些对象被回收调了呢
通过Object类中 finalize() 方法,当垃圾回收器确定不再有对象的引用时,会自动调用该对象的 finalize方法,finalize方法也叫做析构函数。

示例:
// 在类中重写 finalize() 方法
public class Student {
@Override
protected void finalize() throws Throwable {
super.finalize();
System.out.println("finalize执行了");
}
}

// 测试类
// 创建一个Student对象
Student stu = new Student();
stu = null; // 引用指向为空
// 垃圾回收器检测到 有一个Student对象可以被回收,会自动调用该对象的 finalize方法
// 运行垃圾回收器,回收可以被回收的对象
System.gc();

getProperty(String key)

作用:根据key获取指定属性值

参数:String类型值

返回值:String

示例:
// 获取键值对信息
String javaVersion = System.getProperty("java.version");
System.out.println("javaVersion = " + javaVersion);

getProperties()

作用:获取当前系统的所有的属性,静态方法

参数:无

返回值:Properties类型

示例:
// 获取当前系统的所有的属性
Properties properties = System.getProperties(); // 得到一个对象,键值对的形式
// 使用 Properties类中 实例的方法 list(), list()方法中参数 是一个PrintStream类的对象,
// System.out 就是一个 PrintStream 类型的对象,把out传入
properties.list(System.out); // 打印到控制台

面试题:final 和 finally 和 finalize方法的区别

final:属于java关键字,修饰属性,方法,或者类,修饰属性表示常量,又分为基本数据类型和引用数据类型,修饰方法不能被重写,修饰类表示不能被继承。

finally:属于Java关键字,用于异常处理,表示任何情况都执行的代码块。

finalize:属于Object类中的方法,性质属于析构函数,表示当前对象被回收就自动调用的方法。
// 获取平台的默认编码格式
System.getProperty("file.encoding");

Runtime类

Runtime类,此类属于运行时类,每个Java应用程序都将自动创建此类对象,所以不能人为创建。

Runtime类的构造方法是私有的,他的内部有一个静态方法用类创建对象,只能通过getRuntime()方法获取到此类对象,在运行时只能有一个Runtime类的实例对象也成(单例)。

getRuntime()

作用:获取到此Runtime类对象,属于静态方法

参数:无

返回值:Runtime类型

示例:
// 获取Runtime类对象
Runtime runtime = Runtime.getRuntime();

exec(String command)

作用:执行本地可执行文件,属于实例方法

参数:文件绝对路径

返回值:空

示例:
Runtime runtime = Runtime.getRuntime();
// 执行可执行程序
runtime.exec("D:\\funny\\10秒让整个屏幕开满玫瑰花\\点我.exe");

exit(int status)

作用:退出JVM虚拟机,属于实例方法

参数:1代表强制退出,-1代表正常退出虚拟机

返回值:空

示例:
Runtime runtime = Runtime.getRuntime();
runtime.exit(1);

freeMemory()

作用:获取JVM空闲内存,单位为字节,属于实例方法

参数:空

返回值:String

示例:
Runtime runtime = Runtime.getRuntime();
runtime.freeMemory()

maxMemory()

作用:获取JVM最大内存,单位为字节,属于实例方法

参数:空

返回值:String

示例:
Runtime runtime = Runtime.getRuntime();
runtime.maxMemory()

totalMemory()

作用:获取JVM总内存,单位为字节,属于实例方法

参数:空

返回值:String

示例:
Runtime runtime = Runtime.getRuntime();
runtime.totalMemory()

gc()

作用:运行垃圾回收器,属于实例方法,System类中gc()方法使用底层使用就是此方法。

参数:空

返回值:无

示例:
Runtime runtime = Runtime.getRuntime();
runtime.gc();

String类

构造方法

// 通过使用平台的默认字符集解码指定的字节数组来构造新的String
// 第一个参数是 byte数组对象,第二个参数是数组偏移量,第三个参数是转换的长度
String(byte[] bytes, int offset, int length)

// 分配一个新的 String ,其中包含字符数组参数的子阵列中的字符
// 第一个参数是 char数组对象,第二个参数是数组偏移量,第三个参数是转换的长度
String(char[] value, int offset, int count)

length()

作用:获取字符串长度

参数:空

返回值:无

示例:
String str1 = "abc hello world";
int length = str1.length();
System.out.println("length = " + length); // length = 15

equals()

作用:比较字符串内容

参数:比较的字符串

返回值:布尔值

示例:
String str1 = "abc hello world";
String str2 = "abc hello world aqua";
boolean result = str1.equals(str2);
System.out.println("result = " + result); // false

equalsIgnoreCase()

作用:比较字符串内容,忽略大小写

参数:比较的字符串

返回值:布尔值

示例:
String str1 = "abc hello world";
String str2 = "abc hello World";
boolean result02 = str1.equalsIgnoreCase(str2);
System.out.println("result02 = " + result02); // true

toLowerCase()

作用:转换为小写

参数:无

返回值:String类型

示例:

String str2 = "abc hello World";
String lowerCase01 = str2.toLowerCase();
System.out.println("lowerCase01 = " + lowerCase01); // abc hello world

toUpperCase()

作用:转换为小写

参数:无

返回值:String类型

示例:

String str2 = "abc hello World";
String UpperCase02 = str2.toUpperCase();
System.out.println("UpperCase02 = " + UpperCase02); // ABC HELLO WORLD

concat()

作用:字符串连接,同样可以使用 "+" 也可以连接。

参数:无

返回值:String类型

示例:
String str1 = "abc hello world";
String str2 = "abc hello World";
String concatString = str1.concat(str2);
System.out.println("concatString = " + concatString); // abc hello worldabc hello World

indexOf(String str)

作用:搜索第一个出现的字符ch(或字符串value),如果没有找到,返回-1,找到返回对应下标

参数:string类型

返回值:int类型

示例:

String str1 = "abc hello World";
int index = str1.indexOf("abc");
System.out.println("index = " + index); //0

indexOf(int str) 方法重载

作用:搜索第一个出现的字符的 ASCII 编码,如果没有找到,返回-1,找到返回对应下标。

参数:int类型

返回值:int类型

示例:

String str1 = "abc hello World";
int index = str1.indexOf(97); // a 的 ASCII 编码为97
System.out.println("index = " + index); // 0

lastIndexOf(String str)

作用:查找某个字符/字符串在字符串中最后一次出现的位置,如果没有找到,返回-1,找到返回对应下标。

参数:string类型

返回值:int类型

示例:

String str1 = "abc hello World";
int index = str1.lastIndexOf("o");
System.out.println("index = " + index); // 11

lastIndexOf(int str)

作用:查找某个字符的 ASCII 编码在字符串中最后一次出现的位置,如果没有找到,返回-1,找到返回对应下标。

参数:int类型

返回值:int类型

示例:

String str1 = "abc hello World";
int index3 = str1.lastIndexOf(99);
System.out.println("index3 = " + index3); // 2

substring(int beginIndex)

作用:根据指定开始下标截取字符串,截取到末尾。

参数:int类型

返回值:String类型

示例:

String str1 = "abc hello World";
String substring01 = str1.substring(2);
System.out.println("substring01 = " + substring01); // c hello world

substring(int beginIndex,int endIndex)

作用:根据指定开始下标截取字符串,截取到指定位置 (包前不包后)。

参数:第一个参数是开启截取的字符串,第二个参数是截取字符串末尾

返回值:String类型

示例:
String str1 = "abc hello World";
String substring02 = str1.substring(2,5);
System.out.println("substring01 = " + substring02); // c h

trim()

作用:去除字符串的前后空格,中间空格不影响。

参数:无

返回值:String类型

示例:
String str3 = " abc hello World ";
String str4 = str3.trim();
System.out.println("str4 = " + str4); // abc hello World

split(String regex)

作用:根据指定条件拆分字符串。

参数:String类型

返回值:String类型数组

示例:
String str1 = "abc hello World";
String[] splitRes = str1.split(" "); // 按照空格进行拆分
String[] splitRes = str1.split(""); // 会把每一个字符进行拆分
for (int i = 0; i < splitRes.length; i++) {
System.out.println(splitRes[i]);
}

charAt(int index)

作用:根据指定下标返回对应位置的字符

参数:Int类型

返回值:String类型

示例:
String str1 = "abc hello World";
char c = str1.charAt(1);
System.out.println("c = " + c); // 2

contains(CharSequence s)

作用:判断字符串是否包含某一个字符串

参数:String类型

返回值:布尔值

示例:
String str1 = "abc hello World";
boolean ac = str1.contains("ac");
System.out.println("ac = " + ac); // false

endsWith(String suffix)

作用:判断字符串是否以某一个字符串结尾

参数:String类型

返回值:布尔值

示例:
String str1 = "abc hello World";
boolean res = str1.endsWith("World");
System.out.println("res = " + res); // false

startsWith(String prefix)

作用:判断字符串是否以某一个字符串开头

参数:String类型

返回值:布尔值

示例:
String str1 = "abc hello World";
boolean res = str1.endsWith("abc");
System.out.println("res = " + res); // true

isEmpty()

作用:判断字符串长度是否为0

参数:无

返回值:布尔值

示例:
String str1 = "abc hello World";
boolean res = str1.isEmpty();
System.out.println("res = " + res); // false

replace(char oldChar, char newChar)

作用:替换字符串中指定的字符,符合条件的全部替换。也可以替换字符串

参数:

返回值:

示例:
String str1 = "abc hello World";
String replace = str1.replace('a', 'A');
String replace02 = str1.replace("abc", "AEC");
System.out.println("replace = " + replace); // Abc hello World
System.out.println("replace02 = " + replace02); // AEC hello world

toCharArray()

作用:将字符串中的每个字符拆分为一个字符数组,返回一个新的 char[] 数组

参数:无

返回值:返回一个新的 char[] 类型的数组,包含字符串中的所有字符,顺序一致

示例:
public class Main {
public static void main(String[] args) {
String str = "hello";
char[] charArray = str.toCharArray();

// 遍历输出字符数组
for (char c : charArray) {
System.out.println(c);
}
}
}

valueOf(Object b)

作用:将指定内容转换为字符串,此方法是静态方法。

参数:任何类型都可以

返回值:String类型

示例:
String res1 = String.valueOf(5612);
System.out.println("res1 = " + res1); // 5612
// 效果如同
int a = 5612;
String s1 = a + "";
System.out.println("s1 = " + s1); // 5612

intern()

作用:调用intern()方法,会先去字符串常量池中,检查是否有当前字符串完全相同的内容,如果有则直接引用常量池中的地址,如果没有,则先将字符串内容存进常量池中,再引用地址。此方法属于实例方法。

参数:无

返回值:String对象

示例:
String str1 = "abc";
String str2 = new String("abc").intern();
System.out.println(str1 == str2); // true

getBytes()

作用:将字符串转为字节数组。

参数:无

返回值:byte [] 字节数组

示例:
String str = "世界你好 hello world 666";
byte[] bytes = str.getBytes();

相关面试题

String类相关面试题:

1.String类内底层实现

String类底层帮我们维护的是一个char数组,即我们创建的每一个字符串对象都以char数组的形式来保存。

2.String类对象是否可以改变?

不可改变 String对象是不可改变的,任何对String对象内容的修改,都会产生一个新的字符串对象。

3.为什么String类是不可变对象

原因1:底层为char数组维护的String对象,而数组的长度是固定的。

原因2: 此数组为final修饰,表示不能指向新的地址,同时也使用private修饰,表示不能被外界访问。

原因3:String类是final修饰的,不能被其他类继承。

4.有没有什么方式改变String对象的内容?

有 使用反射可以修饰字符串对象的内容

5.String类中intern()方法的作用:

调用intern() 会先去字符串常量池中 检查是否有当前字符串完全相同的内容 如果有则直接引用以存在常量池中的地址 如果没有 则先将字符串内容存进常量池 然后再引用地址

这两种写法是等价的,效果完全一样,都是声明一个 char 类型的数组变量,名字叫 marriage
char[] marriage;
char marriage[];

char marriage[]; 也合法,早期 C 风格写法,Java 兼容但不推荐

String类的底层实现

Serializable // 序列化,串行化
comparable // 可比较的,可排序的
charSequence // 字符序列

String类底层帮我们维护的是一个char数组,我们创建的每一个字符串对象都以char数组的形式来保存。

String类对象是否可以改变

不可改变,String类对象是不可改变的,任何对String对象的修改,都会产生一个新的字符串对象。

例如:
String str1 = "abc"; // new char[]{'a','b','c'}
str1 += "hello"; // new char[]{'a','b','c','h','e','l','l','o'}
// 数组的特点,长度固定,数据类型相同,空间连续
System.out.print(str1 + "str1")

为什么String类是不可变对象

原因1:底层为char数组维护的String对象,而数组的长度是固定的。
原因2:此数组为final修饰,表示不能指向新的地址,同时使用private修饰,表示不能被外界访问。
原因3:String类是final修饰的,表示不能被继承。

有没有方式改变String类对象的内容

有,使用反射可以修改字符串对象的内容。

笔试题1

常量存在于 常量池 中,常量池存在于堆空间中。
常量池中的数据,是不允许重复的,如果不存在则存入,同时把堆中的地址赋值给str1。
如果存在,则把第一次存进入的堆中的地址赋值给str1。两者的地址是相同的,是同一个。
String str1 = "abc"; // 存在常量池中
String str2 = "abc"; // 存在常量池中
String str3 = new String("abc"); // 存在堆内存中

System.out.println(str1 === str2) // true
System.out.println(str1 === str3) // false

笔试题2

// 使用等号赋值的,字面量,编译期间可以确定内容是什么。
// 使用new对象的,是在程序运行期间确定内容

String str4 = "x" + "y" + "z" // 字面量的方式拼接字符串,在编译期间,编译器会自动优化为 "xyz"
String str5 = new String("xyz") // 使用new对象的,是在程序运行期间才可以确定内容

System.out.println(str4 === str5) // true

笔试题3

// 字符串拼接的规律:
// 常量 + 常量 是在常量池中,先看常量池中是否存在,如果不存在,则先存放,再引用地址。如果存在,则直接引用地址。

// 其他三种情况,都在堆中创建新的对象。

String str6 = "hello ";
String str7 = "world";

String str8 = str6 + str7;
String Str9 = "hello world";

String str10 = "hello " + "world";

String str11 = str6 + "world";
String str12 = "hello " + str7;

System.out.println(str8 == Str9); // false
System.out.println(Str9 == str10); // true
System.out.println(str11 == str12); // false

StringBuffer类

线程安全,可变的字符序列。和String类功能一样,但可以修改。

StringBuffer和String类都实现了同一个接口 CharSequence

异同点

  • 都实现了接口:CharSequence(用于描述一系列字符序列)。

  • 都有 toString() 方法(用于获取字符串表示)。

  • 都能通过 charAt(int index)length() 等方法访问字符。

方法

append()

作用:追加元素,此方法属于实例方法,内存中只有这一个对象。StringBuffer是可变对象。

参数:基本数据类型都可以

返回值:StringBuffer对象

示例:
// 定义一个 StringBuffer类 对象
StringBuffer str1 = new StringBuffer();
// 追加char类型
str1.append('a');
// 追加String类型
str1.append("hello");
// 追加int类型
str1.append(123);
// 追加float类型
str1.append(3.6F);
// 追加布尔类型
str1.append(true);
// 打印输出
System.out.println("str1: " + str1); // str1: ahello1233.6true

delete()

作用:根据指定下标范围删除指定字符

参数:int start,int end:第一个参数是开始下标,第二个参数是结束下标

返回值:StringBuffer对象

示例:
StringBuffer str2 = str1.delete(0, 2);
System.out.println("str2: " + str2);

deleteCharAt()

作用:根据指定下标删除指定字符

参数:int index:删除指定下标位置的字符

返回值:StringBuffer对象

示例:
StringBuffer str3 = str2.deleteCharAt(0);
System.out.println("str3 = " + str3);

insert()

作用:根据指定下标位置添加字符串

参数:int start,Object obj:第一个参数是下标位置,第二个参数是object对象(什么都可以)

返回值:StringBuffer对象

示例:

StringBuffer aqua = str3.insert(0, "aqua");
System.out.println("aqua = " + aqua);

replace()

作用:用指定的字符串替换指定的范围

参数:int start,int end,String str 第一个参数是开始下标,第二个参数是结束下标,第三个参数是指定的字符串。

返回值:StringBuffer对象

示例:
StringBuffer kawaii = aqua.replace(5, 10, "kawaii");
System.out.println("kawaii = " + kawaii);

reverse()

作用:翻转字符串

参数:无

返回值:StringBuffer对象

示例:
StringBuffer str4 = kawaii.reverse();
System.out.println("str4 = " + str4);

setCharAt()

作用:修改指定下标位置的字符

参数:int index,char ch :第一个参数是指定下标,第二个参数是char字符。

返回值:空

示例:
str4.setCharAt(1,'H');
System.out.println("str4 = " + str4);

StringBuilder类

一个可变的字符序列,和StringBuffer类一样的API(方法形参返回值,构造都一样),但是不保证同步(线程不安全)。和String类功能一样。

  • 实现了接口:CharSequence(用于描述一系列字符序列)

String类和StringBuffer和StringBuilder类区别

String是不可变字符串对象
StringBuffer和StringBuilder属于可变字符串对象

String 是线程不安全的 JDK1.0
StringBuffer是线程安全的 JDK1.0 效率低
StringBuilder是线程不安全 JDK1.5 效率高

Date类

包名:java.util.Date,此类提供有用于处理日期的各种方法

构造方法

无参构造
Date()
有参构造
Date(long date)

示例:
// 无参构造
Date date = new Date();
System.out.println("date = " + date); // 默认调用了Date类中重写的toString方法

// 有参构造1
// 传入的年份 + 1900 = 真正的年份
// 传入的月份 + 1 = 真正月份
Date date1 = new Date(125,6,21);
System.out.println("date1 = " + date1);

// 有参构造2 System.currentTimeMillis() 当前系统时间毫秒数
Date date2 = new Date(System.currentTimeMillis());
System.out.println("date2 = " + date2);

属性

方法

getXXX()

getYear(),getMonth(),getDate(),getDate(),getDay(),getHours(),getMinutes(),getSeconds()
作用:获取年月日时分秒

参数:无

返回值:Int类型

示例:
Date date1 = new Date();

int month = date1.getMonth();
System.out.println("time = " + month);

System.out.println("年份" + (date1.getYear() + 1900));
System.out.println("月份" + (date1.getMonth() + 1));
System.out.println("一月中的天" + date1.getDate());
System.out.println("一周中的天" + date1.getDay());
System.out.println("时" + date1.getHours());
System.out.println("分" + date1.getMinutes());
System.out.println("秒" + date1.getSeconds());

getTime()

作用:获取当前时间时间戳

参数:无

返回值:Long类型

示例:
Date date = new Date();
long time = date.getTime();
System.out.println("time = " + time); // time = 1753085144329

日期格式化类

包名:java.text;SimpleDateFormat类

SimpleDateFormat类作用:字符串转为日期对象,日期对象转为字符串对象。

构造方法

无参构造:使用默认模版格式转换以及解析
SimpleDateFormat()

有参构造:使用指定模版转换以及解析
SimpleDateFormat(String pattern)


// 使用SimpleDateFormat类中的方法转换Date对象
SimpleDateFormat sdf = new SimpleDateFormat(); // 使用无参构造,以默认格式转化以及解析日期
String dateStr = sdf.format(date); // 将Date对象转String
Date date1 = sdf.parse("25-7-21 下午4:15"); // 将String对象转Date对象
System.out.println("dateStr = " + dateStr); // dateStr = 25-7-21 下午4:12
System.out.println("date1 = " + date1); // Mon Jul 21 16:15:00 CST 2025

// 模版1 yyyy-MM-dd HH:mm:ss
// 模版2 yyyy年MM月dd日 HH:mm:ss
SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss"); // 使用有参构造
String dateStr1 = sdf1.format(date);
System.out.println("dateStr1 = " + dateStr1); // dateStr1 = 2025年07月21日 16:18:44

属性

方法:使用他的父类 DateFormat 抽象类中的方法

format()

作用:将日期对象转为字符串

参数:Date对象

返回值:String类型

示例:
SimpleDateFormat sdf = new SimpleDateFormat(); // 使用无参构造,以默认格式转化以及解析日期
String dateStr = sdf.format(date); // 将Date对象转String
System.out.println("dateStr = " + dateStr); // dateStr = 25-7-21 下午4:12

parse()

作用:将字符串转为Date对象

参数:String类型

返回值:Date对象

示例:
SimpleDateFormat sdf = new SimpleDateFormat(); // 使用无参构造,以默认格式转化以及解析日期
Date date1 = sdf.parse("25-7-21 下午4:15"); // 将String对象转Date对象
System.out.println("date1 = " + date1); // Mon Jul 21 16:15:00 CST 2025

Calendar类

包名:java.util.Calendar ;calendar类;抽象类;提供关于时间获取的方法

构造方法:不能new对象

属性:

static int YEAR 作用:get现场编号和 set表示年份。 
static int MONTH 作用:get和 set字段号表示月份。
static int DATE 作用:get和 set字段编号表示该月的日期
static int HOUR
static int MINUTE
static int SECOND
static int WEEK_OF_YEAR 一年中的第几周
static int DAY_OF_YEAR 一年中的第几天
static int DAY_OF_WEEK 一周中的第几天

方法:

get()

作用:返回给定日历字段

参数:Calendar类中的Int静态属性

返回值:Int类型

示例:
// 创建对象
Calendar calendar = Calendar.getInstance();

// 使用实例方法
int year = calendar.get(Calendar.YEAR);
int date = calendar.get(Calendar.DATE);

System.out.println("date = " + date); // date = 21
System.out.println("year = " + year); // year = 2025

System.out.println("年" + calendar.get(Calendar.YEAR));
System.out.println("月" + calendar.get(Calendar.MONTH));
System.out.println("日" + calendar.get(Calendar.DAY_OF_MONTH));
System.out.println("时:" + calendar.get(Calendar.HOUR));
System.out.println("分:" + calendar.get(Calendar.MINUTE));
System.out.println("秒:" + calendar.get(Calendar.SECOND));
System.out.println("一年中的第几天:" + calendar.get(Calendar.DAY_OF_YEAR));
System.out.println("一周中的第几天:" + calendar.get(Calendar.DAY_OF_WEEK));

静态方法:

getInstance()

作用:使用默认时区和区域设置获取日历对象(通过子类创建的对象)

参数:无

返回值:Calendar对象

示例:
Calendar calendar = Calendar.getInstance(); // 直接通过类名访问静态方法

JDK1.8新增日期API

LocalDate类

一个不可变的日期时间对象,只包含年月日,只能表示年月日。

构造方法:无

静态方法

now():通过类名直接访问

作用:获取当前系统时间

参数:无

返回值:LocalDate对象

示例:
LocalDate localDate = LocalDate.now();
System.out.println("localDate = " + localDate); // localDate = 2025-07-21

of()

作用:根据传入的年月日构造当前类实例

参数:int year,int month,int dayOfMonth:年月日

返回值:LocalDate对象

示例:

getXXXX():实例方法

getYear(),getMonth(),getDayOfMonth()

作用:获取年月日

参数:无

返回值:Int类型

示例:
// 通过of 静态方法 创建LocalDate对象
LocalDate of = LocalDate.of(2024,12,12);
System.out.println("localDate2 = " + of); // localDate2 = 2024-12-12


// 获取年月日信息
int year = of.getYear();
System.out.println("year = " + year); // year = 2024

System.out.println(of.getMonth());
System.out.println(of.getDayOfMonth());
System.out.println(of.getDayOfYear());
System.out.println(of.getDayOfWeek());

LocalTime类

一个不可变的日期时间对象,只包含时分秒,只能表示时分秒。

构造方法:无

静态方法

now()

作用:获取当前系统时间

参数:无

返回值:LocalTime对象

示例:
LocalTime localTime = LocalTime.now();
System.out.println("localTime = " + localTime); // localTime = 17:11:09.412

of()

作用:根据传入的时分秒构造当前类实例

参数:int hour,int minutes,int seconds:时分秒

返回值:LocalTime对象

示例:
LocalTime localTime1 = LocalTime.of(17, 30, 00);
System.out.println("localTime1 = " + localTime1); // localTime1 = 17:30

getXXXX():实例方法

getHour(),getMinute(),getSeconds()

作用:获取年月日

参数:无

返回值:Int类型

示例:
LocalTime localTime1 = LocalTime.of(17, 30, 00);
System.out.println("localTime1 = " + localTime1); // localTime1 = 17:30

int hour = localTime1.getHour();
System.out.println("hour = " + hour); // hour = 17

LocalDateTime类

一个不可变的日期时间对象,包含年月日时分秒,能表示年月日时分秒。

构造方法:无

静态方法

now()

作用:获取当前系统时间

参数:无

返回值:LocalDateTime对象

示例:
LocalDateTime localDateTime = LocalDateTime.now();
System.out.println("localDateTime = " + localDateTime); // localDateTime = 2025-07-21T17:14:18.473

of()

作用:根据传入的时分秒构造当前类实例

参数:int year,int month,int dayOfMonth,int hour,int minutes,int seconds:年月日时分秒

返回值:LocalDateTime对象

示例:
LocalDateTime localDateTime1 = LocalDateTime.of(2025, 12, 25, 18, 00, 00);
System.out.println("localDateTime1 = " + localDateTime1); // localDateTime1 = 2025-12-25T18:00

getXXXX():实例方法

getHour(),getMinute(),getSeconds(),getYear(),getMonth(),getDayOfMonth()

作用:获取年月日时分秒

参数:无

返回值:Int类型

示例:
LocalDateTime localDateTime1 = LocalDateTime.of(2025, 12, 25, 18, 00, 00);
int hour = localDateTime1.getHour();
System.out.println("hour = " + hour); // hour = 18

BigInteger类

比Long类型还要大的整数,BigInteger,任意长度任意大小的整数。属于Number类的子类。

构造方法

BigInteger(Sting str) : 通过字符串创建实例

方法:实例方法(加减乘除)

add()

作用:加

参数:BigInteger对象

返回值:BigInteger 类型

示例:
BigInteger bigInteger1 = new BigInteger("3141592653");
BigInteger bigInteger2 = new BigInteger("3141592654");

BigInteger sum = bigInteger1.add(bigInteger2);
System.out.println("sum = " + sum); // sum = 6283185307

subtract()

作用:减

参数:BigInteger对象

返回值:BigInteger 类型

示例:
BigInteger bigInteger1 = new BigInteger("3141592653");
BigInteger bigInteger2 = new BigInteger("3141592654");

BigInteger sub = bigInteger1.subtract(bigInteger2);
System.out.println("sub = " + sub); // sub = -1

multiply()

作用:乘法

参数:BigInteger对象

返回值:BigInteger 类型

示例:
BigInteger bigInteger1 = new BigInteger("3141592653");
BigInteger bigInteger2 = new BigInteger("3141592654");

BigInteger res = bigInteger1.multiply(bigInteger2);
System.out.println("res = " + res); // res = 9869604400525171062

divide()

作用:除法

参数:BigInteger对象

返回值:BigInteger 类型

示例:
BigInteger bigInteger1 = new BigInteger("3141592653");
BigInteger bigInteger2 = new BigInteger("3141592654");

BigInteger res = bigInteger1.divide(bigInteger2);
System.out.println("res = " + res); // res = 0 只保留整数

BigDecimal类

任意长度任意精度的浮点数。可以保存任意精度 任意长度的小数

构造方法

BigDecimal(Sting str) : 通过字符串创建实例

方法:实例方法(加减乘除)

add()

作用:加

参数:BigDecimal对象

返回值:BigDecimal 类型

示例:
BigDecimal bigDecimal1 = new BigDecimal("56785676578978526574852632574163526352.6598963598759652203895659565");
BigDecimal bigDecimal2 = new BigDecimal("567826352.6598963598759");

BigDecimal add = bigDecimal1.add(bigDecimal2);
System.out.println("add = " + add);

BigDecimal subtract = bigDecimal1.subtract(bigDecimal2);
System.out.println("subtract = " + subtract);

BigDecimal multiply = bigDecimal1.multiply(bigDecimal2);
System.out.println("multiply = " + multiply);


BigDecimal divide = bigDecimal1.divide(bigDecimal2, 6, RoundingMode.HALF_UP);
System.out.println("divide = " + divide);

subtract()

作用:减

参数:BigDecimal对象

返回值:BigDecimal 类型

示例:
BigDecimal bigDecimal1 = new BigDecimal("56785676578978526574852632574163526352.6598963598759652203895659565");
BigDecimal bigDecimal2 = new BigDecimal("567826352.6598963598759");

BigDecimal subtract = bigDecimal1.subtract(bigDecimal2);
System.out.println("subtract = " + subtract);

multiply()

作用:乘法

参数:BigDecimal 对象

返回值:BigDecimal 类型

示例:
BigDecimal bigDecimal1 = new BigDecimal("56785676578978526574852632574163526352.6598963598759652203895659565");
BigDecimal bigDecimal2 = new BigDecimal("567826352.6598963598759");

BigDecimal multiply = bigDecimal1.multiply(bigDecimal2);
System.out.println("multiply = " + multiply);

divide()

作用:除法

参数:BigDecimal 对象

返回值:BigDecimal 类型

示例:
BigDecimal bigDecimal1 = new BigDecimal("56785676578978526574852632574163526352.6598963598759652203895659565");
BigDecimal bigDecimal2 = new BigDecimal("567826352.6598963598759");

BigDecimal divide = bigDecimal1.divide(bigDecimal2, 6, RoundingMode.HALF_UP);
System.out.println("divide = " + divide);