一、String类、StringBuffer类和StrinrgBuilder类
String类
1、String特性
字符串是常量,用双引号引起来表示。它们的值在创建之后不能更改,并且字符串 String 类型本身是 final 声明的,意味着我们不能继承 String。
String的内存结构
2、String常用方法
1.2.1构造方法
String str1 = new String();
System.out.println(str1 + 'd');//d
String str2 = new String("abcd");//abcd
char[] charArray = new char[] {'D','E','F'};
String str3 = new String(charArray);//DEF
byte[] arr = {97,98,99};
String str4 = new String(arr);//abc
1.2.2常用方法
字符串获取功能
String s = "abcdefghijkabc";
System.out.println("字符串的长度为:" + s.length());//14
System.out.println("字符串第一个字符为:" + s.charAt(0));//a
System.out.println("字符c第一次出现的索引为:" + s.indexOf('c'));//2
System.out.println("字符c最后一次出现的索引:" + s.lastIndexOf('c'));//13
System.out.println("字符ab第一次出现的索引:" + s.indexOf("ab"));//0
System.out.println("字符ab最后一次出现的索引:" + s.lastIndexOf("ab"));//11
字符串转换功能
String str = "abcd";
char[] charArray = str.toCharArray();//将字符串转换为数组
for (int i = 0; i < charArray.length; i++) {
if(i != charArray.length- 1){
System.out.print(charArray[i] +",");
}else{
System.out.println(charArray[i]);
}
}//a,b,c,d
//将int类型转换为String类型 "12"
System.out.println(String.valueOf(12));
System.out.println(str.toUpperCase());//转换为大写 ABCD
System.out.println( str.toLowerCase());//转换为小写 abcd
字符串替换和去除
String str1 = "hello";
System.out.println(str1.replace("he","HE"));//HEllo
String str2 = " h e l l o ";
System.out.println(str2.trim());//去除两端空格 h e l l o
System.out.println(str2.replace(" ",""));//去除所有空格 hello
字符串判断
String str1 = "string";
String str2 = "str";
System.out.println(str1.startsWith("str"));//判断字符串以str开始 true
System.out.println(str1.endsWith("ing"));//判断字符串以ing结束 true
System.out.println(str1.contains("s"));//判断字符串包含s true
System.out.println(str1.isEmpty());//判断是否为空 false
System.out.println(str1.equals(str2));//判断两个字符串是否相等 false
字符串的截取和分割(截取索引不包括右边界)
String str = "广东省-中山市-五桂山";
System.out.println(str.substring(4));//中山市-五桂山
System.out.println(str.substring(4, 6));//中山
//分割
String[] split = str.split("-");//
for (int i = 0; i < split.length; i++) {
if (i != split.length - 1) {
System.out.print(split[i] + ",");
} else {
System.out.print(split[i]);
}
}//广东省,中山市,五桂山
StringBuffer类和StringBulider类
String 对象是不可变对象,虽然可以共享常量对象,但是对于频繁字符串的修改和拼接操作,效率极低,空间消耗也比较高。因此,在lang包中提供了可变字符序列StringBuffer 和 StringBuilder 类。
三者区别:
String:不可变的字符序列(底层使用 char[]数组存储),可以用 + 进行连接。
StringBuffer:可变的字符序列,线程安全,但效率低(底层使用 char[]数组存储),不可以使用 + 进行连接,并且无法使用equals方法
StringBuffer:可变的字符序列,线程不安全,但效率高(底层使用 char[]数组存储),不可以使用 + 进行连接,并且无法使用equals方法
1.常用API
public static void main(String[] args) {
System.out.println("----添加----");
add();
System.out.println("----移除----");
remove();
System.out.println("----修改----");
alter();
}
public static void add(){
StringBuffer stringBuffer = new StringBuffer();
stringBuffer.append("hello");
System.out.println(stringBuffer);
stringBuffer.insert(2, "123");
System.out.println(stringBuffer);
}
public static void remove(){
StringBuffer stringBuffer = new StringBuffer("hello");
stringBuffer.delete(1,3);
System.out.println(stringBuffer);
stringBuffer.deleteCharAt(2);
System.out.println(stringBuffer);
stringBuffer.delete(0,stringBuffer.length());
System.out.println(stringBuffer);
}
public static void alter(){
StringBuffer stringBuffer = new StringBuffer("hello");
stringBuffer.setCharAt(0,'H');
System.out.println(stringBuffer);
stringBuffer.replace(1,5,"ELLO");
System.out.println(stringBuffer);
System.out.println(stringBuffer.reverse());
}
2.三者时间消耗测试
private static final int TIMES = 100000;
public static void main(String[] args) {
example09.testString();
example09.testStringBuffer();
example09.testStringBuild();
}
//String 时间效率测试
public static void testString(){
long start = System.currentTimeMillis();
String str = "";
for (int i = 0; i < TIMES; i++) {
str += "test";
}
long end = System.currentTimeMillis();
System.out.println(" String testTime: " + (end -start));
}
//StringBuffer 时间测试
public static void testStringBuffer(){
long start = System.currentTimeMillis();
StringBuffer stringBuffer = new StringBuffer();
for (int i = 0; i < TIMES; i++) {
stringBuffer.append("test");
}
long end = System.currentTimeMillis();
System.out.println("StringBuffer testTime: " + (end - start));
}
//StringBuild 时间测试
public static void testStringBuild(){
long start = System.currentTimeMillis();
StringBuilder stringBuilder = new StringBuilder();
for (int i = 0; i < TIMES; i++) {
stringBuilder.append("test");
}
long end = System.currentTimeMillis();
System.out.println("StringBuilder testTimes: " + (end -start));
}
由此可以看出StringBuilder速度最快
二、System类和Runtime类
System
System类定义了一些与系统相关的属性和方法,它所提供的属性和方法都是静态的,要引用这些属性和方法,直接使用System类调用。
常用方法
在进行数组复制时,目标数组必须有足够的空间来存放拷贝的元素,否则会发生角标越界异常。
int[] fromArray = {1,2,3,4,5,6};
int[] toArray = {6,7,8,9,10,11,12};
//从fromArray数组第 2 索引位置开始复制4个元素道toArray数组索引为3开始的位置
System.arraycopy(fromArray,2,toArray,3,4);
for (int i = 0; i < toArray.length; i++) {
System.out.print(toArray[i] + " ");
}//6 7 8 3 4 5 6
垃圾回收器
对象为null,当被识别到的时,对其在内存中进行释放,它的finalize()方法会被自动调用,因此可以在类中通过定义finalize()方法观察对象何时被释放。
public class gcTest{
public static void main(String[] args) {
Person p1 = new Person();
Person p2 = new Person();
p1 = null;
p2 = null;
System.gc();
for (int i = 0; i < 100000; i++) {
}
}
}
class Person{
public void finalize(){
System.out.println("垃圾回收...");
}
}
运行结果
Runtime
Runtime类用于表示虚拟机运行时的状态,它用于封装JVM虚拟机进程。通过Runtime run = Runtime.getRuntime();获得实例。
常用方法
三、Math类和Random类
Math类
1.常用方法
代码演示
System.out.println(Math.abs(-1));//1
System.out.println(Math.sqrt(4));//2.0
System.out.println(Math.ceil(3.4));//4.0
System.out.println(Math.floor(3.9));//3.0
System.out.println(Math.round(5.9));//6
System.out.println(Math.max(2,3));//3
System.out.println(Math.min(2,5));//2
System.out.println(Math.random());//0-1之间的随机数
System.out.println(Math.pow(2,3));//8.0
Random类
两个构造方法,一个无参,以当前时间戳为默认种子。一个有参,则是传入指定的参数作为种子。
带种子的随机数生成器,每次生成的随机数可能不同,但每一遍生成的随机数是相同的。
不带种子的随机数生成器,每次生成的随机数可能不同;每一遍生成的随机数也可能不同
Random random = new Random(20);
for (int i = 0; i < 10; i++) {
//生成10个0-100之间的随机数
System.out.print(random.nextInt(100) + " ");
}//53 36 1 61 5 95 33 55 93 88 无论执行多少次,结果都相同
常用方法
Random random = new Random();
System.out.println(random.nextDouble());
System.out.println(random.nextFloat());
System.out.println(random.nextInt());
System.out.println(random.nextInt(10));//生成0-10之间的随机整数
获取指定范围随机数
公式:rand.nextInt(MAX - MIN + 1) + MIN;
Random random = new Random();
//生成30-64之间的随机整数
System.out.println(random.nextInt(64-30 + 1) + 30);//运行结果随机生成39
四、日期时间类
主要类
Instant类
Instant now = Instant.now();
System.out.println("当前时间:" + now);
Instant instant = Instant.ofEpochMilli(1000 * 60 * 60 * 24);
System.out.println("计算机元年增加毫秒数为:" + instant);
Instant instant1 = Instant.ofEpochSecond(1000 * 60 * 24);
System.out.println("计算机元年增加秒数为:" + instant1);
System.out.println("获取秒值为:" + Instant.parse("2007-12-03T10:15:30.44Z").getEpochSecond());
System.out.println("获取纳秒值为:" + Instant.parse("2007-12-03T10:15:30.44Z").getNano());
System.out.println("当前时间对象获取:" + Instant.from(now));
运行结果
LocalDate类
LocalData类仅用来表示日期。通常表示的是年份和月份,该类不能代表时间线上的即时信息,只是日期的描述。
LocalTime类
LocalTime类用来表示时间,通常表示的是小时分钟秒。与LocalData类一样,该类不能代表时间线上的即时信息,只是时间的描述。
LocalDateTime类
LocalDataTime类是LocalData类与LocalTime类的综合,它即包含日期也包含时间。
Period类
Period主要用于计算两个日期的间隔,并提供了获取年月日的三个常用方法,分别是 getYears()、getMonths()和getDays()。
LocalDate total = LocalDate.of(2018, 12, 11);
LocalDate now = LocalDate.now();//2024-10-18
Period between = Period.between(total, now);
System.out.println("时间间隔为:" + between.getYears() + "年");//时间间隔为:5年
System.out.println("时间间隔为:" + between.getMonths() + "月");//时间间隔为:10月
System.out.println("时间间隔为:" + between.getDays() + "日");//时间间隔为:7日
Duration类
Duration类基于时间值,其作用范围是天、时、分、秒、毫秒和纳秒。
LocalTime start = LocalTime.now();
LocalTime end = LocalTime.of(20, 13, 23);
Duration between = Duration.between(start, end);
System.out.println("时间间隔为:" + between.toNanos() + "纳秒");
System.out.println("时间间隔为:" + between.toMillis() + "毫秒");
System.out.println("时间间隔为:" + between.toHours() + "小时");
结果