第5单元 Java API
API:application programming interface 应用程序编程接口:
提供实现特定功能的类(变量和方法)
5.1 字符串类:
String类、StringBuffer类和StringBuilder类
字符串:
定义:包含在一个成对双引号内,由任意个字符组成的一串字符。"" "a" "abcde" String name="张三" int x=10;
类型:引用数据类型,传地址
分类:(1)String类;(2)StringBuffer类;(3)StringBuilder类
位置:java.lang包(此包不需要导入,直接使用)。
5.1.1 String类
1、定义:String类一旦创建完成,其内容和长度不可改变,因此又叫字符串常量。
String类初始化方法:2种
2、String类初始化方法
(1)字符串常量值接赋值,初始化String对象。 例子:String str1="abc";
(2)String类构造方法,初始化String对象
1)String();2)String(String value);
3)String(char[] value);4)String(byte[] bytes)
例子5-1 String类的初始化
public class Example01 {
public static void main(String[] args) throws Exception {
String str1 = new String(); // 创建一个空的字符串
String str2 = new String("abcd"); // 创建一个内容为abcd的字符串
char[] charArray = new char[] { 'D', 'E', 'F' }; // 创建一个内容为字符数组的字符串
String str3 = new String(charArray);
byte[] arr = {97,98,99}; // 创建一个内容为字节数组的字符串
String str4 = new String(arr);
System.out.println("a" + str1 + "b");
System.out.println(str2);
System.out.println(str3);
System.out.println(str4);
}
}
5.1.2 String类常规操作
1、字符串获取功能:
(1)字符串长度:length();(2)指定位置的字符:charAt();
(3)指定字符或子字符串在字符的位置:1)索引(第一次):indexOf;2)索引(最后一次):lastIndexOf()
例子5-2 字符串获取功能
public class Example02 {
public static void main(String[] args) {
String s = "ababcdedcba"; // 定义字符串s
System.out.println("字符串的长度为:" + s.length());
System.out.println("字符串中第一个字符:" + s.charAt(0));
System.out.println("字符c第一次出现的位置:" + s.indexOf('c'));
System.out.println("字符c最后一次出现的位置:" + s.lastIndexOf('c'));
System.out.println("子字符串ab第一次出现的位置:" + s.indexOf("ab"));
System.out.println("子字符串ab字符串最后一次出现的位置:" + s.lastIndexOf("ab"));
}
}
2、字符串的转换操作:
(1)字符串转字符数组:toCharArray();(2)int型整数转换成字符串;valueOf();
(3)字符串字符大小写转换:toUpperCase()、toLowerCase()
例子5-3 字符串转换
public class Example03 {
public static void main(String[] args) {
String str = "abcd";
System.out.print("将字符串转为字符数组后的结果:");
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]); // 数组的最后一个元素后面不加逗号
}
}
System.out.println("将int值转换为String类型之后的结果:" + String.valueOf(12));
System.out.println("将字符串转换成大写之后的结果:" + str.toUpperCase());
System.out.println("将字符串转换成小写之后的结果:" + str.toLowerCase());
}
}
3、字符串替换和去除空格操作:
(1)字符串替换:replace(oldstr,newstr);(2)字符串去除两端空格:trim()
注:这个两个字符串,返回一个新的字符串
例子5-4 字符串替换和去除空格
public class Example04 {
public static void main(String[] args) {
String s = "itcast"; // 字符串替换操作
System.out.println("将it替换成cn.it的结果:" + s.replace("it", "cn.it"));
String s1 = " i t c a s t "; // 字符串去除空格操作
System.out.println("去除字符串两端空格后的结果:" + s1.trim());
System.out.println("去除字符串中所有空格后的结果:" + s1.replace(" ", ""));
}
}
4、字符串判断操作:返回布尔值
(1)以指定字符串开始,结束:startsWith(),endsWith()
(2)包含某个字符串:contains()
(3)字符串是否为空:isEmpty()
(4)字符串内容(字符)相等:equals()
例子5-5 字符串判断操作
public class Example05 {
public static void main(String[] args) {
String s1 = "String"; // 声明一个字符串
String s2 = "Str";
System.out.println("判断是否以字符串Str开头:" + s1.startsWith("Str"));
System.out.println("判断是否以字符串ng结尾:" + s1.endsWith("ng"));
System.out.println("判断是否包含字符串tri:" + s1.contains("tri"));
System.out.println("判断字符串是否为空:" + s1.isEmpty());
System.out.println("判断两个字符串是否相等" + s1.equals(s2));
}
}
注意:
(1)字符串内容相等:equals()方法
(2) 字符串对象的地址相同:==
例子:字符串相等
String s1 = new String("abc");
String s2 = new String("abc");
System.out.println(str1==str2); //false
System.out.println(str1.equals(str2)); //tru
5、字符串截取和分割:
(1)字符串截取:substring(n): 从第n个索引截取到最后
; substring(n,m) 从第n个索引截取到第m-个索引
(2)字符串分割:String[] split():字符串按照指定字符分割成子字符串,并保存在字符串数组中。
例子5-6 字符串截取和分割
public class Example06 {
public static void main(String[] args) {
String str = "石家庄-武汉-哈尔滨";
System.out.println("从第5个字符截取到末尾的结果:" + str.substring(4)); // 字符串截取操作
System.out.println("从第5个字符截取到第6个字符的结果:" + str.substring(4, 6));
System.out.print("分割后的字符串数组中的元素依次为:");
String[] strArray = str.split("-"); // 将字符串转换为字符串数组
for (int i = 0; i < strArray.length; i++) {
if (i != strArray.length - 1) { // 如果不是数组的最后一个元素,在元素后面加逗号
System.out.print(strArray[i] + ",");
} else { // 数组的最后一个元素后面不加逗号
System.out.println(strArray[i]);
}
}
}
}
注意:字符串索引越界
例子5-7 字符串索引越界异常
public class Example07 {
public static void main(String[] args) {
String s = "itcast";
System.out.println(s.charAt(8));
}
}
5.1.3 StringBuffer类
问题:String类的字符串是一个常量,创建之后,其内容和长度不可改变。只能创建新的字符串进行修改。
1、StringBuffer类:
(1)定义:字符串容器(字符串缓冲区),
(2)特点:StringBuffer类的字符串内容和长度可变,即对字符串修改(添加或删除字符),只是对原对象进行修改,不会产生新的StringBuffer对象。
2、StringBuffer类常见操作:
(1)添加:append(String str); insert(int index,String str)
(2)删除:delete(int start,int end), deleteCharAt(int index)
(3)修改:setChartAt(int index,char ch); replace(int start, int end, String s)
reverse()
例子5-8 StringBuffer类常见操作
public class Example08 {
public static void main(String[] args) {
System.out.println("1、添加------------------------");
add();
System.out.println("2、删除------------------------");
remove();
System.out.println("3、修改------------------------");
alter();
}
public static void add() {
StringBuffer sb = new StringBuffer(); // 定义一个字符串缓冲区
sb.append("itcast"); // 在末尾添加字符串
System.out.println("append添加结果:" + sb);
sb.insert(2, "123"); // 在指定位置插入字符串
System.out.println("insert添加结果:" + sb);
}
public static void remove() {
StringBuffer sb = new StringBuffer("itcastcn");
sb.delete(1, 5); // 指定范围删除
System.out.println("删除指定位置结果:" + sb);
sb.deleteCharAt(2); // 指定位置删除
System.out.println("删除指定位置结果:" + sb);
sb.delete(0, sb.length()); // 清空缓冲区
System.out.println("清空缓冲区结果:" + sb);
}
public static void alter() {
StringBuffer sb = new StringBuffer("itcastcn");
sb.setCharAt(1, 'p'); // 修改指定位置字符
System.out.println("修改指定位置字符结果:" + sb);
sb.replace(1, 3, "qq"); // 替换指定位置字符串或字符
System.out.println("替换指定位置字符(串)结果:" + sb);
System.out.println("字符串翻转结果:" + sb.reverse());
}
}
5.1.4 StringBuilder类
1、StringBuilder类与StringBuffer类比较:
(1)相同:都可以对字符串进行修改而不产生新对象。
两者方法可共用。
(2)区别:StringBuffer线程安全的,不能同步访问,效率低。
StringBuilder线程不安全,能同步访问,效率高。
例子5-9 StringBuilder类与StringBuffer类运行效率
public class Example09{
private static final int TIMES = 100000;
public static void main(String[] args) {
Example09.testString();
Example09.testStringBuffer();
Example09.testStringBuilder();
}
public static void testString() { //String时间效率测试
long startTime = System.currentTimeMillis(); //返回以毫秒为单位的当前时间
String str = "";
for (int i = 0; i < TIMES; i++) {
str += "test";
}
long endTime = System.currentTimeMillis();
System.out.println("String test usedtime: " + (endTime - startTime));
}
public static void testStringBuffer() { //StringBuffer时间效率测试(线程安全)
long startTime = System.currentTimeMillis();
StringBuffer str = new StringBuffer();
for (int i = 0; i < TIMES; i++) {
str.append("test");
}
long endTime = System.currentTimeMillis();
System.out.println("StringBuffer test usedtime: " + (endTime – startTime));
}
public static void testStringBuilder() { //StringBuffer时间效率测试(非线程安全)
long startTime = System.currentTimeMillis();
StringBuilder str = new StringBuilder();
for (int i = 0; i < TIMES; i++) {
str.append("test");
}
long endTime = System.currentTimeMillis();
System.out.println("StringBuilder test usedtime: " + (endTime – startTime));
}
}
String类、StringBuffer类和StringBuilder类区别:
(1)String类表示字符串常量(创建之后,其长度和内容不可变),一般仅用于表示字符串数据类型。
StringBuffer类和StringBuilder类表示字符串容器(创建之后,其长度和内容可变),适用于对字符串进行增,删,改等操作。
(StringBuffer线程安全的,效率低; StringBuilder线程不安全,效率高。)
(2)equals()方法只用于String类,不适用于StringBuffer类和StringBuilder类。
String s1=new String("abc");
String s2=new String("abc");
System.out.println(s1.equals(s2)); //true
StringBuffer sb1=new StringBuffer("abc");
StringBuffer sb2=new StringBuffer("abc");
System.out.println(sb1.equals(sb2)); //false
StringBuilder sbr1=new StringBuilder("abc");
StringBuilder sbr2=new StringBuilder("abc");
System.out.println(sbr1.equals(sbr2)); //false
(3) String类对象可以使用“+”进行链接,但不适用于StringBuffer类和StringBuilder类(append()方法)。
String s1="a";
String s2="b";
String s3=s1+s2;
System.out.println(s3);
StringBuffer sb1=new StringBuffer("a");
StringBuffer sb2=new StringBuffer("b");
StringBuffer sb3=sb1+sb2; //错误
5.2 System类和Runtime类
5.2.1 System类
1、定义:定义了与系统相关的属性(成员)和方法。
2、特点:System类中的属性(成员)和方法都是静态的,可用System类名直接调用。
3、位置:java.lang包(此包可直接使用,不需要导入)
3、方法:
(1)arraycopy(Object src,int srcPos, Object dest, int destPos, int length):将数组从源数组复制到目标数组中
源数组,源数组起始位置,目标数组,目标数组起始位置,复制长度
例子5-10 arraycopy()方法使用
public class Example10 {
public static void main(String[] args) {
int[] fromArray = { 10, 11, 12, 13, 14, 15 }; // 源数组
int[] toArray = { 20, 21, 22, 23, 24, 25, 26 }; // 目标数组
System.arraycopy(fromArray, 2, toArray, 3, 4); // 拷贝数组元素
System.out.println("拷贝后的数组元素为:");
for (int i = 0; i < toArray.length; i++) {
System.out.println(i + ": " + toArray[i]);
}
}
}
注:数组复制,目标数组必须由足够的空间存储元素,否则发生索引越界异常。
(2)currentTimeMillis():获取当前系统时间,返回值是long型值,时间戳(与19070年1月1日0点0分0秒之间的差,单位是毫秒)
例子5-11 currentTimeMillis()方法使用
public class Example11 {
public static void main(String[] args) {
long startTime = System.currentTimeMillis(); // 循环开始时的当前时间
int sum = 0;
for (int i = 0; i < 1000000000; i++) {
sum += i;
}
long endTime = System.currentTimeMillis();// 循环结束后的当前时间
System.out.println("程序运行的时间为:"+(endTime - startTime)+"毫秒");
}
}
(3)getProperties()和getProperty()
getProperties():获取当前系统所有的属性(属性以以键值对的形式),返回一个Properties对象。
Properties.propertyNames():返回所有的键Enumeration对象
Enumeration类:hasMoreElement():nextElement()
getProperty():根据系统属性名,得到对应属性值。
例子5-12 getProperties()和getProperty()方法
import java.util.*;
public class Example12 {
public static void main(String[] args) {
Properties properties = System.getProperties(); // 获取当前系统全部属性,属性以键值对形式保存
Enumeration propertyNames = properties.propertyNames(); // 获得系统所有键的集合,返回Enumeration()对象
while (propertyNames.hasMoreElements()) { //对Enumeration()对象,进行遍历
String key = (String) propertyNames.nextElement(); // 获取系统属性当前的键key
String value = System.getProperty(key); // 获得当前键key对应的值value
System.out.println(key + "--->" + value);
}
}
}
(4)gc():立即启用垃圾回收机制
垃圾对象:对象没有任何的引用或者对象=null;
垃圾回收机制:
特点:清除垃圾对象,腾出内存空间。 (垃圾对象:不再引用任何内存的对象)
启动:(1)JVM自动启动;(2)System.gc()告知JVM立即启动垃圾回收
对象在内存中被释放,会自动调用对象的finalize()方法,通过在类中定义finalize()方法(该方法返回值必须为 viod),查看对象是否被回收。
例子5-13 gc()调用垃圾回收机制和finalize()方法
class Person {
public void finalize() { // 下面定义的finalize方法会在垃圾回收前被调用
System.out.println("对象将被作为垃圾回收...");
}
}
public class Example13{
public static void main(String[] args) {
Person p1 = new Person(); // 下面是创建了两个Person对象
Person p2 = new Person();
p1 = null; // 下面将变量置为null,让对象成为垃圾
p2 = null;
System.gc(); // 调用方法进行垃圾回收
for (int i = 0; i < 1000000; i++) { // 为了延长程序运行的时间
}
}
}
对象将被作为垃圾回收...
对象将被作为垃圾回收...
(5)exit(int status):退出当前的JVM
5.2.2 Runtime类
1、定义:表示当前Java虚拟机运行时的状态,封装Java虚拟机。
2、特点:使用Java命令启动JVM都只对应一个Runtime实例
3、Runtime类构造方法私有,不能直接实例化,只能通过调用getRuntime()方法返回实例对象
Runtime rt = Runtime.getRuntime(); // 获取Runtime实例化对象
4、方法
(1)getRuntime():获取Runtime类实例对象。
(2)freeMemory(),maxMemory(),totalMemory(),availableProcessors()
(3)exec(String command):根据指定路径,执行相应的可执行文件
调用exec()方法,返回一个Process对象(进程对象)
(4)destroy():杀掉当前进程
例子5-14 获取当前虚拟机信息
public class Example14 {
public static void main(String[] args) {
Runtime rt = Runtime.getRuntime(); // 获取Runtime实例化对象
System.out.println("处理器的个数: " + rt.availableProcessors()+"个");
System.out.println("空闲内存数量: " + rt.freeMemory() / 1024 / 1024 + "M");
System.out.println("最大可用内存数量: " + rt.maxMemory() / 1024 / 1024 + "M");
System.out.println("虚拟机中内存总量: " + rt.totalMemory() / 1024 / 1024 + "M");
}
}
例子5-15 操作系统进程
import java.io.IOException;
public class Example15{
public static void main(String[] args) throws IOException {
Runtime rt = Runtime.getRuntime(); // 创建Runtime实例对象
rt.exec("notepad.exe"); // 调用exec()方法,打开Windows自带的笔记本程序
}
}
例子 destroy():杀掉当前进程
public class Example{
public static void main(String[] args) throws Exception {
Runtime rt = Runtime.getRuntime(); // 创建Runtime实例对象
Process process=rt.exec("notepad.exe"); // 得到进程对象
Thread.sleep(3000); //进程休眠3秒
process.destroy(); //杀掉进程
}
}
5.3 Math类和Random类
5.3.1 Math类
1、定义:提供静态方法(类名直接调用方法),实现数学计算。
2、位置:在java.lang包中,不需要导入,直接用
3、方法
(1)abs();
(2)sqrt()。(结果:double型)
sqrt(4):2.0
(3)ceil():大于等于指定值的最小值。
(4)floor():小于等于指定值的最大值。
(5)round():浮点数四舍五入。
(6)max();
(7)min();
(8)random():生成一个大于等于0小于1的随机数。(结果:double型)
(9)pow(a,b):a的b次方。(结果:double型)
pow(2,3):8.0
例子5-16 Math类方法
public class Example16 {
public static void main(String[] args) {
System.out.println("计算绝对值的结果: " + Math.abs(-10));
System.out.println("求大于参数的最小整数: " + Math.ceil(5.6));
System.out.println("求小于参数的最大整数: " + Math.floor(-4.2));
System.out.println("对小数进行四舍五入后的结果: " + Math.round(-4.6));
System.out.println("求两个数的较大值: " + Math.max(2.1, -2.1));
System.out.println("求两个数的较小值: " + Math.min(2.1, -2.1));
System.out.println("生成一个大于等于0.0小于1.0随机值: " +
Math.random());
System.out.println("开平方的结果: "+Math.sqrt(4));
System.out.println("指数函数的值: "+Math.pow(2, 3));
}
}
5.3.2 Random类:
1、定义:在指定的取值范围内产生随机数
2、位置:在java.uitl包中,使用时需导入
3、方法
(1)构造方法:产生伪随机数生成器
1)Random():每次使用对象,产生不同随机数(以当前时间戳作为种子)
2)Random(long seed):每次使用对象,产生相同随机数(以seed作为种子)
例子5-17 Random()方法:无参数(没指定种子)
import java.util.Random;
public class Example17 {
public static void main(String args[]) {
Random r = new Random(); // 不传入种子
for (int x = 0; x < 10; x++) {
System.out.println(r.nextInt(100)); // 随机产生10个[0,100)之间的整数
}
}
}
例子5-18 Random()方法:有参数(指定种子)
import java.util.Random;
public class Example17 {
public static void main(String args[]) {
Random r = new Random(); // 不传入种子
for (int x = 0; x < 10; x++) {
System.out.println(r.nextInt(100)); // 随机产生10个[0,100)之间的整数
}
}
}
(2)产生伪随机数的方法
1)nextFloat():生成[0.0~1.0)之间的float型数值
2)nexDouble():生成[0.0~1.0)之间的double型数值
3)nextInt():生成-2^31~2^31-1的int值
4)netInt(n):生成[0~n)之间的int型数值
例子5-19 Random类产生不同类型随机数
import java.util.Random;
public class Example19 {
public static void main(String[] args) {
Random r1 = new Random(); // 创建Random实例对象
System.out.println("产生float类型随机数: " + r1.nextFloat());
System.out.println("产生double类型的随机数:" + r1.nextDouble());
System.out.println("产生int类型的随机数:" + r1.nextInt());
System.out.println("产生0~100之间int类型的随机数:" + r1.nextInt(100));
}
}
5.4 日期时间类
定义:专门用于处理日期和时间的类
位置:在java.time包中,使用时需导入
日期时间类:Instant类、LocalDate类、LocalTime类、LocalDateTime类、Period和Duration类
Clock类
Java时间标准格式:1970-01-01T00:00.000Z
5.4.1 Instant类
1、定义:Instant类表示某个时间,从1970-01-01T00:00:00到当前时间的毫秒值
2、方法:
(1)now():从系统时钟获取当前时刻的一个实例对象。
(2)ofEpochSecond(long epochSecond):获取Java时间元年增加秒数后的一个Instant实例
(3)ofEpochMill(long epochMilli): 获取Java时间元年增加毫秒数后的一个Instant实例
(4)parse(CharSequenece text): 从文本字符串中获取一个Instant实例
(5)from(TemporalAccessor temporal): 从时间对象获取一个Instant实例
(5)getEpochSecond(): 返回指定时间到现在的秒值。
(7)getNano(): 返回指定时间到现在的纳秒值。
例子5-20 Instant类常用方法
import java.time.Instant;
public class Example20 {
public static void main(String[] args) { // Instant 时间戳类从1970 -01 - 01 00:00:00 截止到当前时间的毫秒值
Instant now = Instant.now();
System.out.println("从系统获取的当前时刻为:"+now);
Instant instant = Instant.ofEpochMilli(1000 * 60 * 60 * 24);
System.out.println("计算机元年增加毫秒数后为:"+instant);
Instant instant1 = Instant.ofEpochSecond(60 * 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实例为:"+Instant.from(now));
}
}
5.4.2 LocalDate类
1、定义:LocalDate类仅用于表示日期(年、月和日),不能表示小时、分钟和秒。
2、方法:
(1)获取日期对象的方法
1)now():从系统时钟获取当前日期对象
2)of(year,month,day):从指定日期获取日期对象
例子:
LocalDate now=LocalDate.now();
LocalDate date=LocalDate.of(2022,12,4);
(2)常用方法
1)getYear():获取年份
2)getMonthValue():获取月份
3)getDayOfMonth():获取月份第几天
4)format(DateTimeFormatter formatter):使用指定的格式化程序格式化日期
DateTimeFormatter.ofPattern("yyyy年MM月dd日")
5)isBefore():判断是否在指定日期之前
6)isAffter():判断是否在指定日期之后
7)isEqual():判断是否等于指定日期
8)isLeapYear():判断是否时闰年
9) parse(CharSequence text):从文本字符串中获取LocalDate实例
10)plusYears(),plusMonths(),plusDays():增加指定年、月、日
11)minYears(),minMonths(),minDays():减少指定年、月、日
12)withYear(),withMonth(),withDayofYear():指定年、月、日
例子5-21 LocalDate类常用方法
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
public class Example21 {
public static void main(String[] args) {
LocalDate now = LocalDate.now(); //获取日期时分秒
LocalDate of = LocalDate.of(2015, 12, 12);
System.out.println("1. LocalData的获取及格式化的相关方法--------");
System.out.println("从LocalData实例获取的年份为:"+now.getYear());
System.out.println("从LocalData实例获取的月份:"+now.getMonthValue());
System.out.println("从LocalData实例获取当天在本月的第几天:"+ now.getDayOfMonth());
System.out.println("将获取到的Loacaldata实例格式化为:"+ now.format(DateTimeFormatter.ofPattern("yyyy年MM月dd日")));
System.out.println("2. LocalData判断的相关方法----------------");
System.out.println("判断日期of是否在now之前:"+of.isBefore(now));
System.out.println("判断日期of是否在now之后:"+of.isAfter(now));
System.out.println("判断日期of和now是否相等:"+now.equals(of));
System.out.println("判断日期of是否时闰年:"+ of.isLeapYear());
System.out.println("3. LocalData解析以及加减操作的相关方法---------"); //给出一个符合默认格式要求的日期字符串
String dateStr="2020-02-01";
System.out.println("把日期字符串解析成日期对象后为"+LocalDate.parse(dateStr));
System.out.println("将LocalData实例年份加1为:"+now.plusYears(1));
System.out.println("将LocalData实例天数减10为:"+now.minusDays(10));
System.out.println("将LocalData实例指定年份为2014:"+now.withYear(2014));
}
}
5.4.3 LocalTime类和LocalDateTime类
LocalTime类
1、定义:LocalTime类表示具体时间,即小时、分钟和秒。
2、方法:
(1)获取时间对象的方法
1)now():从系统时钟获取当前时间
2)of(hour,minute,second):从指定时间获取时间对象
(2)常用方法
1)getHour():获取小时
2)format(DateTimeFormatter formatter):使用指定的格式化程序格式化时间
DateTimeFormatter.ofPattern("HH:mm:ss")
3)isBefore():判断是否在指定时间之前
4)isAffter():判断是否在指定时间之后
5)isEqual():判断是否等于指定时间
6) parse(CharSequence text):从文本字符串中获取LocalTime实例
10)plusXXXX():增加指定小时、分钟和秒
11)minXXXX():减少指定小时、分钟和秒
12)withXXXX():指定小时、分钟和秒
例子5-22 LocalTime类常用方法
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
public class Example22 {
public static void main(String[] args) {
LocalTime time = LocalTime.now(); // 获取当前时间,包含毫秒数
LocalTime of = LocalTime.of(9,23,23);
System.out.println("从LocalTime获取的小时为:"+time.getHour());
System.out.println("将获取到的LoacalTime实例格式化为:"+time.format(DateTimeFormatter.ofPattern(" HH:mm:ss")));
System.out.println("判断时间of是否在now之前:"+of.isBefore(time));
System.out.println("将时间字符串解析为时间对象后为:"+ LocalTime.parse("12:15:30"));
System.out.println("从LocalTime获取当前时间,不包含毫秒数:"+ time.withNano(0));
}
}
LocalDateTime类
1、定义: LocalDateTime类表示具体日期(年、月和日)和时间(小时、分钟和秒)。
2、默认时间格式:2022-02-29T21:23:26.774
3、方法:包含LocalDate类与 LocalTime类方法。
4、LocalDateTime类特有的转换方法
(1)toLocalDate():
(2)toLocalTime():
例子5-23 LocalDateTime类常用方法
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
public class Example23 {
public static void main(String[] args) {
LocalDateTime now = LocalDateTime.now(); //获取当前年月日,时分秒
System.out.println("获取的当前日期时间为:"+now);
System.out.println("将目标LocalDateTime转换为相应的LocalDate实例:"+ now.toLocalDate());
System.out.println("将目标LocalDateTime转换为相应的LocalTime实例:"+ now.toLocalTime());
DateTimeFormatter ofPattern = DateTimeFormatter.ofPattern("yyyy年MM月dd日 HH时mm分ss秒"); //指定格式
System.out.println("格式化后的日期时间为:"+now.format(ofPattern));
}
}
5.4.4 Duration类和Period类
Duration类和Period类作用:计算时间间隔的方法
Duration类
1、定义:计算两个时间(时、分、秒、毫秒和纳秒)和天的间隔。
2、方法:
(1)between(start,end):两个时间对象的时间间隔
(2)toDays():时间间隔转化成天数的数值
(3)toHours():时间间隔转化成小时的数值
(4)toMinutes():时间间隔转化成为分钟的数值
(5)toMills():时间间隔转化成为毫秒的数值
(6)toNanos():时间间隔转化成为纳秒的数值
例子5-24 Duration类常用方法
import java.time.Duration;
import java.time.LocalTime;
public class Example24{
public static void main(String[] args) {
LocalTime start = LocalTime.now();
LocalTime end = LocalTime.of(20,13,23);
Duration duration = Duration.between(start, end); //间隔的时间
System.out.println("时间间隔为:"+duration.toNanos()+"纳秒");
System.out.println("时间间隔为:"+duration.toMillis()+"毫秒");
System.out.println("时间间隔为:"+duration.toHours()+"小时");
}
}
Period类
1、定义:计算两个日期的间隔。
2、方法:
(1)between(start,end):两个时间对象的时间间隔
(2)getYears():时间间隔转化成年份的数值
(3)getMonths():时间间隔转化成月份的数值
(4)getDays():时间间隔转化成为天的数值
例子5-25 Period类常用方法
import java.time.LocalDate;
import java.time.Period;
public class Example25 {
public static void main(String[] args) {
LocalDate birthday = LocalDate.of(2018, 12, 12);
LocalDate now = LocalDate.now();
Period between = Period.between(birthday, now); //计算两个日期的间隔
System.out.println("时间间隔为"+between.getYears()+"年");
System.out.println("时间间隔为"+between.getMonths()+"月");
System.out.println("时间间隔为"+between.getDays()+"天");
}
}
5.5 包装类
1、定义:将基本数据类型的数值包装为引用数据类的对象(基本类型:数值---->引用类型:对象)
2、位置:java.lang包(此包可直接使用,不需要导入)
3、包装类:Byte类(byte);Character类(char);integer类(int);Short类(short);
Long类(long);Float类(float);Double类(double);Boolean类(boolean)
4、操作:装箱,拆箱
(1)装箱:基本数据类型的值 转化为 引用数据类型的对象(变量值作用包装类构造函数的参数传入)
(2)拆箱: 引用数据类型的对象 转化为 基本数据类型的值 (对象的值直接赋给变量)
特点: 装箱和拆箱都自动完成(赋值语句完成),也可以手动完成
自动 手动
装箱: int a=20; Integer in=new Integer(20);
Integer in=a;
拆箱: int l=in; int l=in.intValue()
例子5-26 自动装箱,自动拆箱
public class Example26 {
public static void main(String args[]) {
int a = 20;
Integer in = a; //自动装箱
System.out.println(in);
int l =in; //自动拆箱
System.out.println(l);
}
}
5、Integer类特有的方法
(1)Integer valueOf(int i):将指定的int值转换为Integer类对象
(2)Integer valueOf(String s):将指定的String形式的数值转换为Integer类对象 "123"
(3)int parseInt(String s):将指定的String形式的数值转换为int类型。
(4)intValue():将Integer类型的值以int类型返回。(手动拆箱)
6、使用包装类的注意点
(1)包装类都重写Object类中的toString()方法,以字符串形式返回被包装的基本数据类型的数值。
(2)除了Character类外,其他包装类都有valueOf(String s)。
使用String形式的数值,创建包装类要求:1)字符串s不能为空,2)字符串s可以解析成相应基本数据类型
(3)除了Character类外,其他包装类都有parseXXX(String s)的静态方法。
使用String形式的数值,转化成相应数据类型的值要求:1)字符串s不能为空,2)字符串s可以解析成相应基本数据类型
例子5-27 Integer类常用方法
public class Example27 {
public static void main(String args[]) {
Integer num = new Integer(20); //手动装箱 Integer num= 20;
int sum = num.intValue() + 10; //手动拆箱
System.out.println("将Integer类值转化为int类型后与10求和为:"+ sum);
System.out.println("返回表示10的Integer实例为:" +
Integer.valueOf(10));
int w = Integer.parseInt("20")+32;
System.out.println("将字符串转化为整数位:" + w);
}
}
5.6 正则表达式
1、定义:由字符组成一种规则,用于验证或者匹配指定字符串是否符合该规则。
5.6.1 元字符
正则表达式由普通字符和特殊字符(元字符)组成的文字模式。
1、定义:在正则表达式中,具有特殊意义的专用字符。
2、作用:用来规定其前导字符(位于元字符前面的字符)在目标对象中的出现模式。
3、常见正则表达式:
(1)\:转义字符;(2)^:正则表达式开头标志;(3)$:正则表达式结尾标志;
(4)*:匹配零次或多次;(5)+:匹配一次或多次;(6)?:匹配一次或零次;(7).:匹配任意字符
(8){n}:匹配n次;(9){n,}:至少匹配n次;(10){n,m}:至少匹配n次,至多匹配m次;(11)x|y:匹配x或y;
(12)[xyz]:字符集合,匹配所包含的任意一个字符;(13)[a-z]:字符范围,匹配指定范围内所的任意字符;
(14)[^a-z]:负值字符范围,匹配任何不在指定范围内所的任意字符;(15)[a-zA-Z]:字符范围,匹配a-z到A-Z;
(16)\d:匹配数字字符0~9;(17)\D:匹配非数字字符;(18)\s:匹配空白字符;(19)\S:匹配非空白字符;
(20)\s:匹配空白字符;(21)\S:匹配非空白字符;(22)\w:匹配单词与数字字符;
(23)\b:单词边界;(24)\B:非单词边界;(25)\A:输入的开头;(26)\G:上一个匹配的结尾;(27)\Z:输入的结尾(如果有的话,仅用于最后的结束符)
5.6.2 Pattern类和Matcher类
Java正则表达式通过java.util.regex包下的Pattern类和Matcher类实现。
1、Pattern类
(1)作用:创建一个正则表达式,即匹配模式
(2)Pattern类实例创建方法:Pattern类构造方法私有,无法直接创建,调用complie(String s)方法创建实例
语法: Pattern p=Pattern.complie("\\w+");
(3)Pattern类常用方法:
1)split(CharSequence input):将字符串按照指定的模式匹配并分割
2)Matcher matcher(CharSequence input):在指定的Pattern实例(对象)模式下,匹配字符串,即创建一个Matcher类对象。
结合Matcher类的pattern()方法,判断Matcher对象的匹配模式,即p。
3)static boolean matches(String regex,CharSequence input):对整个字符串匹配指定模式,返回布尔值
(2个参数)
例子5-28 Pattern类常用方法
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Example28 {
public static void main(String[] args) {
Pattern p=Pattern.compile("\\d+");
String[] str=p.split("我的QQ是:456456我的电话是:0532214我的邮箱是:aaa@aaa.com");
System.out.println("是否匹配Pattern的输入模式"+ Pattern.matches("\\d+","2223")); //true
System.out.println("是否匹配Pattern的输入模式"+ Pattern.matches("\\d+","2223aa")); //false :
Matcher m=p.matcher("22bb23");
System.out.println("返回该Matcher对象是由哪个Pattern对象创建的,即p为:"+ m.pattern());
System.out.print("将给定的字符串分割成Pattern模式匹配为:");
for (int i=0;i<str.length;i++) {
System.out.print(str[i]+ " ");
}
}
}
2、Matcher类
(1)作用:在给定的Pattern实例的模式下,匹配字符串
(2)Matcher类实例创建方法:Matcher类构造方法私有,无法直接创建,通过Pattern.matcher(String s)方法创建实例
语法: Pattern p=Pattern.complie("\\w+");
Matcher m=p.matcher(CharSequence input) //在指定的Pattern实例(对象)模式下,匹配字符串,即创建一个Matcher类对象。
(3)Matcher类常用方法:
1)boolean matches(CharSequence input):对整个字符串匹配指定模式,返回布尔值
2)boolean lookingAt(CharSequence input):对前面的字符串进行匹配,只有匹配到的字符串在最前面才返回true。
3)boolean find(CharSequence input):对字符串进行匹配,不管位置,匹配成功返回true。
4)int end():返回最后一个字符匹配后的偏移量。
5)String group():返回匹配到的子字符串。
6)int start():返回匹配到的子字符串中的索引位置。
例子5-29 Matcher类常用方法
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Example29 {
public static void main(String[] args) {
Pattern p=Pattern.compile("\\d+");
Matcher m=p.matcher("22bb23");
System.out.println("字符串是否匹配:"+ m.matches()); //false
Matcher m2=p.matcher("2223");
System.out.println("字符串是否匹配:"+ m2.matches()); //true
System.out.println("对前面的字符串匹配结果为"+ m.lookingAt()); //true
Matcher m3=p.matcher("aa2223");
System.out.println("对前面的字符串匹配结果为:"+m3.lookingAt()); //false
m.find();
System.out.println("字符串任何位置是否匹配:"+ m.find()); //true
m3.find();
System.out.println("字符串任何位置是否匹配:"+ m3.find()); //true
Matcher m4=p.matcher("aabb");
System.out.println("字符串任何位置是否匹配:"+ m4.find()); //false
Matcher m1=p.matcher("aaa2223bb");
m1.find();
System.out.println("上一个匹配的起始索引::"+ m1.start());
System.out.println("最后一个字符匹配后的偏移量"+ m1.end());
System.out.println("匹配到的子字符串:"+ m1.group()); "2223" '''
}
}
5.6.3 String类对正则表达式的支持
1、boolean matches(String regex):匹配整个字符串
2、String replaceAll(String regex,String replacement):字符串替换
3、String[] split(String regex):字符串拆分
例子5-30 String类对正则表达式的支持
public class Example30{
public static void main(String[] args) {
String str = "A1B22DDS34DSJ9D".replaceAll("\\d+","_"); "A_B_DDS_DSJ_D"
System.out.println("字符替换后为:"+str);
boolean te = "321123as1".matches("\\d+");
System.out.println("字符串是否匹配:"+te);
String s [] ="SDS45d4DD4dDS88D".split("\\d+"); s={"SDS", "d", "DD", "dDS", "D"}
System.out.print("字符串拆分后为:");
for(int i=0;i<s.length;i++){
System.out.print(s[i]+" ");
}
}
}
菜单
本页目录