【Java】7.3 基本类 7.4 Java 8 的日期、时间类
目录
String、StringBuffer和StringBuilder类
Rondom类
BigDecimal类
Java 8 新增的日期、时间包
String、StringBuffer和StringBuilder类
【三者的介绍】
- String类:不可变字符串类,从创立到销毁整个生命周期字符序列不可改变
- StringBuffer类:字符序列可变的字符串。提供:append()、insert()、reverse()、setChar()、setLength()等方法
- StringBuilder类:StringBuild类与StringBuffer类基本相似。不同的是,StringBuffer是线程安全。而StringBuilder无实现线程安全功能,性能略高。(在通常情况下有限选用StringBuilder类)
【String类】
String类提供的方法
- char charAt(index) : 从0~length()-1,返回地index+1个字符
- int compareTo(String) : 比较两个字符串的大小,若相等,则返回0;若不相等返回'h'-'w',即两个字符串第一个不一样的字符ASCII码相减的值
- boolean equals(obj) : 两个字符串是否相同
- String substring(start,end) : 开始,结束截取片段
- String toLowerCase() : 将字符串转为小写
- String toUpperCase() : 将字符串转为大写
【代码实例】
/*** @ClassName: StringTest* @description:String类的方法使用* @author: FFIDEAL* @Date: 2020/3/7 17:28*/public class StringTest {public static void main(String[] args){String str1 = new String("Hello ");String str2 = new String("World!");String str3 = new String("Hello ");//char charAt(index):从0~length()-1System.out.println("str1的第3个字符是:"+str1.charAt(2));//输出:l//int compareTo(String):比较两个字符串的大小,若相等,则返回0;若不相等返回'h'-'w'//第一个不一样的字符ASCII码相减的值System.out.println(str1.compareTo(str2));System.out.println(str1.compareTo(str3));//输出:0//-15//boolean equals(obj):两个字符串是否相同System.out.println(str1.equals(str2));System.out.println(str1.equals(str3));/*输出:* false* true* *///int indexOf():查找某个字符串第一次出现的位置System.out.println(str1.indexOf('l'));System.out.println(str1.indexOf('l',1));/*输出:* 2* 2* *///String substring(start,end):开始,结束截取片段System.out.println(str1.substring(1,3));//String toLowerCase():将字符串转为小写System.out.println(str1.toLowerCase());//String toUpperCase():将字符串转为大写System.out.println(str1.toUpperCase());}
}
【StringBuffer类】
StringBuffer类提供的方法
- StringBuffer reverse() : 将字符串反转,这是对对象的修改
- StringBuffer append(obj) : 追加,参数依附在调用字符串之后
- StringBuffer insert(offset,str) : 插入,在offset位置插入str
- void setCharAt(index,ch) : 字符替换,将第index个字符替换为ch
- void replace(start,end,str) : 字符串替换
- void delete(start,end) : 删除,区间左闭右开
- void setLength(int) : 改变StringBuffer长度,只保留前面的字符串
- int length() : 字符串长度
- int capacity() : 规定的StringBuffer初始容量
/*** @ClassName: StringBufferTest* @description:StringBuffer类的方法使用* @author: FFIDEAL* @Date: 2020/3/6 19:07*/public class StringBufferTest {public static void main(String[] args){StringBuffer stringBuffer = new StringBuffer("Hello world!");//StringBuffer reverse():将字符串反转,这是对对象的修改StringBuffer stringBufferReverse = stringBuffer.reverse();System.out.println(stringBufferReverse);//输出:!dlrow olleH//StringBuffer append(obj):追加,参数依附在调用字符串之后//stringBuffer2.append第一次调用时stringBuffer变为了!dlrow olleH Hello Sun!//第二次调用append时,stringBuffer变为!dlrow olleH Hello Sun!130, 因为都依附在stringBuffer之后的System.out.println(stringBuffer.append(" Hello Sun!"));//输出:!dlrow olleH Hello Sun!System.out.println(stringBuffer.append(130));//输出:!dlrow olleH Hello Sun!130//StringBuffer insert(offset,str):插入,在offset位置插入strSystem.out.println(stringBuffer.insert(2,"☆"));//输出:!d☆lrow olleH Hello Sun!130//void setCharAt(index,ch):字符替换,将第index个字符替换为chstringBuffer.setCharAt(0,'△');System.out.println(stringBuffer);//输出:△d☆lrow olleH Hello Sun!130//void replace(start,end,str):字符串替换stringBuffer.replace(5,6," replace替换方式 " );System.out.println(stringBuffer);//输出:△d☆lr replace替换方式 w olleH Hello Sun!130//void delete(start,end):删除,区间左闭右开stringBuffer.delete(0,1);System.out.println(stringBuffer);//输出:d☆lr replace替换方式 w olleH Hello Sun!130//void setLength(int):改变StringBuffer长度,只保留前面的字符串stringBuffer.setLength(5);System.out.println(stringBuffer);//输出△d☆lr//字符串长度System.out.println(stringBuffer.length());//规定的StringBuffer初始容量System.out.println(stringBuffer.capacity());}
}
【StringBuilder类】
与StringBuffer是一样的,不同的是StringBuffer是线程安全的
Rondom类
Rondom类:生成伪随机数
- 提供nextXxx()方法:生成随机数
ThreadLocalRandom类:多线程下使用生成随机数的
- 提供nextXxx(start,end)方法:在[start,end)范围内生成随机数
import java.util.Random;
import java.util.concurrent.ThreadLocalRandom;/*** @ClassName: RandomTest* @description: Random类是一种伪随机类* 说它伪随机类的因为只要两个Random对象的种子一致,* 且方法调用也一致,他们就是阐述相同的数字序列* @author: FFIDEAL* @Date: 2020/3/8 16:38*/public class RandomTest {public static void main(String[] args){System.out.println("--------第一个种子为50的Random对象----------");Random r1 = new Random(50);System.out.println("r1.nextInt():\t"+r1.nextInt());System.out.println("r1.nextBoolean():\t"+r1.nextBoolean());System.out.println("r1.nextDouble():\t"+r1.nextDouble());System.out.println("r1.nextGaussian():\t"+r1.nextGaussian());System.out.println("r1.nextInt():\t"+r1.nextInt());System.out.println("--------第一个种子为50的Random对象----------");Random r2 = new Random(50);System.out.println("r1.nextInt():\t"+r2.nextInt());System.out.println("r1.nextBoolean():\t"+r2.nextBoolean());System.out.println("r1.nextDouble():\t"+r2.nextDouble());System.out.println("r1.nextGaussian():\t"+r2.nextGaussian());System.out.println("r1.nextInt():\t"+r2.nextInt());System.out.println("--------第一个种子为100的Random对象----------");Random r3 = new Random(100);System.out.println("r1.nextInt():\t"+r3.nextInt());System.out.println("r1.nextBoolean():\t"+r3.nextBoolean());System.out.println("r1.nextDouble():\t"+r3.nextDouble());System.out.println("r1.nextGaussian():\t"+r3.nextGaussian());System.out.println("--------ThreadLocalRandom类----------");//ThreadLocalRandom():多线程下使用生成随机数的ThreadLocalRandom tlr = ThreadLocalRandom.current();//生成一个4~50之间的伪随机整数int var1 = tlr.nextInt(4,50);System.out.println("生成一个4~50之间的伪随机整数:"+var1);//生成一个51~100之间的伪随机浮点数double var2 = tlr.nextDouble(51.0,100.0);System.out.println("生成一个51~100之间的伪随机浮点数:"+var2);}
}/*
--------第一个种子为50的Random对象----------
r1.nextInt(): -1160871061
r1.nextBoolean(): true
r1.nextDouble(): 0.6141579720626675
r1.nextGaussian(): 2.377650302287946
r1.nextInt(): -942771064
--------第一个种子为50的Random对象----------
r1.nextInt(): -1160871061
r1.nextBoolean(): true
r1.nextDouble(): 0.6141579720626675
r1.nextGaussian(): 2.377650302287946
r1.nextInt(): -942771064
--------第一个种子为100的Random对象----------
r1.nextInt(): -1193959466
r1.nextBoolean(): true
r1.nextDouble(): 0.19497605734770518
r1.nextGaussian(): 0.6762208162903859
--------ThreadLocalRandom类----------
生成一个4~50之间的伪随机整数:16
生成一个51~100之间的伪随机浮点数:96.30652015127957
*/
BigDecimal类
要求精度较高的时候使用,在使用时一定要使用String对象作为操作数
import java.math.BigDecimal;/*** @ClassName: BigDecimalTest* @description: BigDecimal类就是能更精确表示、计算浮点数* 由以下代码得知要用String对象作为构造器参数精准度更高* 此外,当我们最后还需要用double类型时,不妨做一个工具类* return b1.add(b2).doubleValue();将double→(使用BigDecimal类)String→double* @author: FFIDEAL* @Date: 2020/3/8 18:29*/public class BigDecimalTest {public static void main(String[] args){BigDecimal f1 = new BigDecimal("0.05");BigDecimal f2 = BigDecimal.valueOf(0.01);BigDecimal f3 = new BigDecimal(0.05);System.out.println("==========使用String作为BigDecimal构造器参数===========");System.out.println("0.05 + 0.01 = " + f1.add(f2));System.out.println("0.05 - 0.01 = " + f1.subtract(f2));System.out.println("0.05 * 0.01 = " + f1.multiply(f2));System.out.println("0.05 / 0.01 = " + f1.divide(f2));System.out.println("==========使用Double作为BigDecimal构造器参数===========");System.out.println("0.05 + 0.01 = " + f3.add(f2));System.out.println("0.05 - 0.01 = " + f3.subtract(f2));System.out.println("0.05 * 0.01 = " + f3.multiply(f2));System.out.println("0.05 / 0.01 = " + f3.divide(f2));/*输出:==========使用String作为BigDecimal构造器参数===========0.05 + 0.01 = 0.060.05 - 0.01 = 0.040.05 * 0.01 = 0.00050.05 / 0.01 = 5==========使用Double作为BigDecimal构造器参数===========0.05 + 0.01 = 0.060000000000000002775557561562891351059079170227050781250.05 - 0.01 = 0.040000000000000002775557561562891351059079170227050781250.05 * 0.01 = 0.00050000000000000002775557561562891351059079170227050781250.05 / 0.01 = 5.000000000000000277555756156289135105907917022705078125* */}
}
valueOf(obj):把数字类型变为字符型
XxxValue():把字符型变为数字类型
//防止一个类的实例化
private 类名(){}
Java 8 新增的日期、时间包
【提供的类和方法】
- Clock类
- instant():代表具体时刻,精确到纳秒
- millis():对应的精确到毫秒
- Duration类
- ofSecond(int)、toMinutes():int秒转为分钟
- offset(clock,int):在时间clock的家畜上在上int分钟
- Instant类
- Instant.now():获取当前时间
- plusSecond(int):将对象增加int秒
- parse(String):用字符串解析Instant对象,格式:parse("2018-02-23T10:22:35.032Z")
- plus(Duration.ofHour().plusMinutes):在原基础上增加X小时xx分钟
- minus(Duration):在原基础上减去X小时xx分钟
- LocalDate类
- LocalDate.now():获取当前时间
- ofYearDay(year,index):输出year的index天
- of(Year,Month,Day):设置年月日
- LocalTime类
- LocalTime.now():获取当前时间
- of(hours,minutes):设置为几点几分
- ofSecondOfDay(index):返回一天中的第index秒
- localDateTime类
- localDateTime.now():获取当前时间
- localDateTime.plusHours(hours).plusMinutes(minutes):在当前时间是加上hours小时minutes分钟
import java.time.*;/*** @ClassName: NewDateTest* @description: java 8 新增的日期时间包* @author: FFIDEAL* @Date: 2020/3/8 22:24*/public class NewDateTest {public static void main(String[] args){System.out.println("========以下是Clock的用法=========");//获取当前ClockClock clock = Clock.systemUTC();//通过Clock获取当前时刻,instant():代表一个具体的时刻,精确到纳秒System.out.println("当前时刻为:" + clock.instant());//获取clock对应的毫秒数,与System.currentTimeMillis()输出相同System.out.println(clock.millis());System.out.println(System.currentTimeMillis());System.out.println("========以下是Duration的用法=========");Duration d = Duration.ofSeconds(6000);System.out.println("6000秒相当于" + d.toMinutes() + "分钟");System.out.println("6000秒相当于" + d.toHours() + "小时");System.out.println("6000秒相当于" + d.toDays() + "天");//在clock的基础上增加6000秒,返回新的ClockClock clock2 = Clock.offset(clock,d);//可以看到clock和clock2相差了1小时40分钟System.out.println("当前时刻加6000秒为:" + clock2.instant());System.out.println("========以下是Instant的用法=========");//获取当前时间Instant instant = Instant.now();System.out.println(instant);//instant添加6000秒,返回新的instantInstant instant1 = instant.plusSeconds(6000);System.out.println(instant1);//根据字符串解析Instant现象,月和日期都要两位数,查源码可得Instant instant2 = Instant.parse("2018-02-23T10:22:35.032Z");System.out.println(instant2);//在instant2上添加5小时40分钟Instant instant3 = instant2.plus(Duration.ofHours(5).plusMinutes(40));System.out.println(instant3);//获取instant3的5天前的时刻Instant instant4 = instant3.minus(Duration.ofDays(5));System.out.println(instant4);System.out.println("========以下是LocalDate的用法=========");//获取当前日期LocalDate localDate = LocalDate.now();System.out.println(localDate);//获取2020年的第202天localDate = LocalDate.ofYearDay(2020,202);System.out.println(localDate);//设置为2020-10-1localDate = LocalDate.of(2020, Month.OCTOBER,1);System.out.println(localDate);System.out.println("========以下是LocalTime的用法=========");//获取当前时间LocalTime localTime = LocalTime.now();System.out.println(localTime);//设置为22:33分localTime = LocalTime.of(22,33);System.out.println(localTime);//返回一天中第45245秒localTime = LocalTime.ofSecondOfDay(45245);System.out.println(localTime);System.out.println("========以下是localDateTime的用法=========");//获取当前的时间和日期LocalDateTime localDateTime = LocalDateTime.now();System.out.println(localDateTime);//在当前日期上加上25小时3分钟LocalDateTime future = localDateTime.plusHours(25).plusMinutes(3);System.out.println(future);System.out.println("========以下是Year、YearMonth、MonthDay的用法=========");Year year = Year.now();//获取当前年份System.out.println("当前年份是:" + year);year = year.plusYears(5);System.out.println("当前年份再加5年是:" + year);//根据指定月份获取YearMonthYearMonth yearMonth = YearMonth.now();//获取当年年月System.out.println(yearMonth);YearMonth ym = year.atMonth(10);System.out.println("Year年10月:" + ym);//当前年月再加5年减3个月ym = ym.plusYears(5).minusMonths(3);System.out.println("当前年月再加5年减3个月是:" + ym);MonthDay monthDay = MonthDay.now();System.out.println("当前月日" + monthDay);//设置为5月23日MonthDay md = monthDay.with(Month.MAY).withDayOfMonth(23);System.out.println("设置为5月23日:" + md);}
}
【Java】7.3 基本类 7.4 Java 8 的日期、时间类相关推荐
- JavaSE10:日期时间类、java比较器、System类、Math类、大数类
写在前面 常用类的学习结束了,现在就简单整理和通过一些小demo来巩固一下吧~ JDK8.0之前的日期时间类 1. java.lang.System类 System类提供的public static ...
- JAVA day13,14 API、Object类、日期时间类(long,Date,Calendar,DateFormat)、String类(字符串,可变长字符串)、正则表达式、包装类
1.API API(Application Programming Interface),应⽤程序编程接⼝.Java API是⼀本程序员的"字 典",是JDK提供给我们使⽤的类的说 ...
- java 日期时间工具_Java日期时间类工具
Java日期时间类工具 Java日期时间类 Date类 Java提供的Date类和Calendar类用于处理日期和时间的类,包括创建日期,时间对象,获取系统当前日期,时间 等操作.但Date类无法实现 ...
- Java 8 日期时间类
Java 8 推出了新的日期时间类,比较常使用的有LocalDateTime,ZonedDateTime,ZoneId,ZoneOffset,DateTimeFormatter,通过这几个类可以使处理 ...
- Java基础知识(二)(Object类的常用方法、日期时间类、System类、StringBuilder类、包装类、Collection集合、Iterator迭代器、泛型、list集Set接口...)
文章目录 Java基础知识(二) 1.Object类的常用方法 1.1 toString方法 1.2 equals方法 1.3 Objects类 2.日期时间类 2.1 Date类 2.2 DateF ...
- Java日期时间类及计算
1. Java中与日期相关的类 1.1 java.util包 类名 具体描述 Date Date对象算是JAVA中历史比较悠久的用于处理日期.时间相关的类了,但是随着版本的迭代演进,其中的众多方法都已 ...
- Day640.Java 8的日期时间类问题 -Java业务开发常见错误
Java 8的日期时间类问题 Hi,阿昌来也! 今天记录分享的是Java 8的日期时间类问题 在 Java 8 之前,我们处理日期时间需求时,使用 Date.Calender 和 SimpleDate ...
- java之进阶语法(Object类及日期时间类)
一.关于Object类 (一)概述 java.lang.object类是java语言的根类,即是所有类的父类. 若一个类没有指定父类,那么默认继承自Object类 object类常用的方法有以下: - ...
- (Java常用类)日期时间类
文章目录 Date类 概述 常用方法 代码演示 DateFormat类 构造方法 格式规则 常用方法 代码演示 Calendar类 概念 获取方式 常用方法 get/set方法 add方法 getTi ...
- Java 8: LocalDate、LocalTime 、LocalDateTime 处理日期时间
JDK8中,新增了三个类,用以处理时间. LocalDate专门处理日期,LocalTime专门处理时间,LocalDateTime包含了日期和时间,而且对于很多复杂的问题,都提供了现成的方法,比如: ...
最新文章
- php $this self,php中self与$this的区别
- 2021年春季学期-信号与系统-第五次作业参考答案-第二小题
- Linux文件系统和文本编辑器
- k近邻算法_K近邻(knn)算法是如何完成分类的?
- 飞天茅台超卖P0事故:请慎用Redis分布式锁!
- 【华为云技术分享】使用sqoop导入mysql数据到hive中
- F5 虚拟机下载 和 试用Key 申请
- mysql复合语句声明开始于_mysql8 参考手册--BEGIN ... END复合语句
- hdu2000——ASCII码排序
- 第一次作业+105032014142
- html5 aria,html - What is HTML5 ARIA? - Stack Overflow
- mysql升更新命令_MySQL升级的3种方法
- MATLAB拟合圆函数
- Oracle 12c新特性--ASMFD(ASM Filter Driver)特性
- linux下拷贝某一时间段的文件
- 联想rd650怎么装系统win7_ThinkServer - RD650 - RAID及系统安装 - 图文
- postgresql主从复制、主从切换
- cad怎么画立体图形教学_cad怎么绘立体图?
- 宏录制流程——例:生成工资条
- c# ListBox控件