1. 大数运算
基本数据类型long ,double 都是有取值范围.遇到超过范围数据怎么办.引入了大数运算对象. 超过取出范围了,不能称为数字了,称为对象
java.math包 : BigInteger大整数, BigDecimal大浮点(高精度,不损失精度)
- BigInteger类使用,计算超大整数的
- 构造方法直接new BigInteger(String str) 数字格式的字符串,长度任意
- BigInteger add(BigInteger b)计算两个BigInteger的数据求和
- BigInteger subtract(BigInteger b)计算两个BigInteger的数据求差
- BigInteger multiply(BigInteger b)计算两个BigInteger的数据求乘积
- BigInteger divide(BigInteger b)计算两个BigInteger的数据求商
public static void main(String[] args) {
//创建大数据运算对象
BigInteger b1 = new BigInteger("2345673456786554678996546754434343244568435678986");
BigInteger b2 = new BigInteger("8765432345678987654323456787654");
//b1+b2 求和
BigInteger add = b1.add(b2);
System.out.println("add = " + add);
//b1 - b2 求差
BigInteger subtract = b1.subtract(b2);
System.out.println("subtract = " + subtract);
//b1 * b2 求积
BigInteger multiply = b1.multiply(b2);
System.out.println("multiply = " + multiply);
//b1 / b2 求商
BigInteger divide = b1.divide(b2);
System.out.println("divide = " + divide);
}
- BigDecimal 类使用,计算超大浮点数
- 构造方法,和BigInteger一样
- 方法 + - * 和BigInteger一样
- BigDecimal divide除法运算
- divide(BigDecimal big,int scalar,int round)方法有三个参数
- big 被除数
- scalar 保留几位
- round 保留方式
- 保留方式 : 该类的静态成员变量
- BigDecimal.ROUND_UP 向上+1
- BigDecimal.ROUND_DOWN 直接舍去
- BigDecimal.ROUND_HALF_UP 四舍五入
public static void main(String[] args) {
BigDecimal b1 = new BigDecimal("3.55");
BigDecimal b2 = new BigDecimal("2.12");
/* System.out.println(b1.add(b2));
System.out.println(b1.subtract(b2));
System.out.println(b1.multiply(b2));*/
//b1 / b2
/**
* 1.674528301886792
* 除不尽,出现异常
* 高精度运算,不能产生无序循环小数,无限不循环
* 保留几位,怎么保留
*
* BigDecimal.ROUND_UP 向上+1
* BigDecimal.ROUND_DOWN 直接舍去
* BigDecimal.ROUND_HALF_UP 四舍五入
*/
BigDecimal divide = b1.divide(b2,3,BigDecimal.ROUND_HALF_UP);
System.out.println("divide = " + divide);
}
2. 日期和日历类
2.1 JDK1.8之前
1、java.util.Date
- new Date():当前系统时间
- new Date(long 毫秒):把该毫秒值换算成日期时间对象
- Date对象.getTime():返回该日期时间对象距离1970-1-1 0.0.0 0毫秒之间的毫秒值
- Date对象.toLocaleString():将date对象转化为字符串
2021-11-5 22:08:57
具体方法参考API文档
@Test
public void test5(){
long time = Long.MAX_VALUE;
Date d = new Date(time);
System.out.println(d);
}
@Test
public void test4(){
long time = 1559807047979L;
Date d = new Date(time);
System.out.println(d);
}
@Test
public void test3(){
Date d = new Date();
long time = d.getTime();
System.out.println(time);//1559807047979
}
@Test
public void test2(){
long time = System.currentTimeMillis();
System.out.println(time);//1559806982971
//当前系统时间距离1970-1-1 0:0:0 0毫秒的时间差,毫秒为单位
}
@Test
public void test1(){
Date d = new Date();
System.out.println(d);
}
2、java.util.TimeZone 获取时区
-
通常,使用
getDefault
获取TimeZone
,getDefault
基于程序运行所在的时区创建TimeZone
。 -
也可以用
getTimeZone
及时区 ID 获取TimeZone
。例如美国太平洋时区的时区 ID 是 “America/Los_Angeles”。
使用getAvailableIDs
获取所有时区
@Test
public void test8(){
// 获取
String[] all = TimeZone.getAvailableIDs();
for (int i = 0; i < all.length; i++) {
System.out.println(all[i]);
}
}
@Test
public void test7(){
TimeZone t = TimeZone.getTimeZone("America/Los_Angeles");
}
常见时区ID:
Asia/Shanghai
UTC
America/New_York
3、java.util.Calendar
Calendar
类是一个抽象类,它为特定瞬间与一组诸如 YEAR
、MONTH
、DAY_OF_MONTH
、HOUR
等 日历字段
之间的转换提供了一些方法,并为操作日历字段(例如获得下星期的日期)提供了一些方法。瞬间可用毫秒值来表示,它是距历元(即格林威治标准时间 1970 年 1 月 1 日的 00:00:00.000,格里高利历)的偏移量。与其他语言环境敏感类一样,Calendar
提供了一个类方法 getInstance
,以获得此类型的一个通用的对象。
(1)getInstance():得到Calendar的对象
(2)get(常量):获取日期
@Test
public void test6(){
Calendar c = Calendar.getInstance();
System.out.println(c);
int year = c.get(Calendar.YEAR);
System.out.println(year);
int month = c.get(Calendar.MONTH)+1; // 0表示第一个月,所以加1
System.out.println(month);
int year = c.get(Calendar.YEAR);
System.out.println(year);
int day1 = c.get(Calendar.DAY_OF_MONTH);
System.out.println(day1);
int day2 = c.get(Calendar.DAY_OF_WEEK);
System.out.println(day2);
int day3 = c.get(Calendar.DAY_OF_YEAR);
System.out.println(day3);
//...
}
@Test
public void test7(){
TimeZone t = TimeZone.getTimeZone("America/Los_Angeles");
//getInstance(TimeZone zone)
Calendar c = Calendar.getInstance(t);
System.out.println(c);
}
(3)改变日期
class Demo2 {
public static void main(String[] args) {
Calendar c = Calendar.getInstance();
System.out.println(c.get(Calendar.YEAR)); // 2021
c.add(Calendar.YEAR, 2);
System.out.println(c.get(Calendar.YEAR)); // 2023
}
}
class Demo2 {
public static void main(String[] args) {
Calendar c = Calendar.getInstance();
System.out.println(c.get(Calendar.YEAR)); // 2021
c.set(1994,11,01);
System.out.println(c.get(Calendar.YEAR)); // 1994
}
}
4、java.text.SimpleDateFormat 日期格式化类
SimpleDateFormat用于日期时间的格式化。
// 将Date对象转化为自定义格式的字符串
@Test
public void test9(){
Date d = new Date();
SimpleDateFormat sf = new SimpleDateFormat("yyyy年MM月dd日 HH时mm分ss秒 SSS毫秒 E Z");
//把Date日期转成字符串,按照指定的格式转
String str = sf.format(d);
System.out.println(str); // 2021年11月05日 22时35分30秒 051毫秒 星期五 +0800
// 将格式化的字符串转化为Date对象
@Test
public void test10() throws ParseException{
String str = "2019年06月06日 16时03分14秒 545毫秒 星期四 +0800";
// 这里的Format格式,必须与要解析的字符串内容完全匹配
SimpleDateFormat sf = new SimpleDateFormat("yyyy年MM月dd日 HH时mm分ss秒 SSS毫秒 E Z");
Date d = sf.parse(str);
System.out.println(d); // Thu Jun 06 16:03:14 CST 2019
}
}
2.2 JDK1.8之后
Java1.0中包含了一个Date类,但是它的大多数方法已经在Java 1.1引入Calendar类之后被弃用了。而Calendar并不比Date好多少。它们面临的问题是:
- 可变性:象日期和时间这样的类对象应该是不可变的。Calendar类中可以使用三种方法更改日历字段:set()、add() 和 roll()。
- 偏移性:Date中的年份是从1900开始的,而月份都是从0开始的。
- 格式化:格式化只对Date有用,Calendar则不行。
- 此外,它们也不是线程安全的,不能处理闰秒等。
可以说,对日期和时间的操作一直是Java程序员最痛苦的地方之一。第三次引入的API是成功的,并且java 8中引入的java.time API 已经纠正了过去的缺陷,将来很长一段时间内它都会为我们服务。
Java 8 吸收了 Joda-Time 的精华,以一个新的开始为 Java 创建优秀的 API。
- java.time – 包含值对象的基础包
- java.time.chrono – 提供对不同的日历系统的访问。
- java.time.format – 格式化和解析时间和日期
- java.time.temporal – 包括底层框架和扩展特性
- java.time.zone – 包含时区支持的类
Java 8 吸收了 Joda-Time 的精华,以一个新的开始为 Java 创建优秀的 API。新的 java.time 中包含了所有关于时钟(Clock),本地日期(LocalDate)、本地时间(LocalTime)、本地日期时间(LocalDateTime)、时区(ZonedDateTime)和持续时间(Duration)的类。
1、日期时间:LocalDate、LocalTime、LocalDateTime
LocalDate:日期对象(年月日)
LocalTime:时间对象(时分秒)
LocalDateTime:日期时间对象(年月日+时分秒)
方法 | 描述 |
---|---|
now() / now(ZoneId zone) | 静态方法,根据当前时间创建对象/指定时区的对象 |
of() | 静态方法,根据指定日期/时间创建对象 |
getDayOfMonth()/getDayOfYear() | 获得月份天数(1-31) /获得年份天数(1-366) |
getDayOfWeek() | 获得星期几(返回一个 DayOfWeek 枚举值) |
getMonth() | 获得月份, 返回一个 Month 枚举值 |
getMonthValue() / getYear() | 获得月份(1-12) /获得年份 |
getHours()/getMinute()/getSecond() | 获得当前对象对应的小时、分钟、秒 |
withDayOfMonth()/withDayOfYear()/withMonth()/withYear() | 将月份天数、年份天数、月份、年份修改为指定的值并返回新的对象 |
with(TemporalAdjuster t) | 将当前日期时间设置为校对器指定的日期时间 |
plusDays(), plusWeeks(), plusMonths(), plusYears(),plusHours() | 向当前对象添加几天、几周、几个月、几年、几小时 |
minusMonths() / minusWeeks()/minusDays()/minusYears()/minusHours() | 从当前对象减去几月、几周、几天、几年、几小时 |
plus(TemporalAmount t)/minus(TemporalAmount t) | 添加或减少一个 Duration 或 Period |
isBefore()/isAfter() | 比较两个 LocalDate |
isLeapYear() | 判断是否是闰年(在LocalDate类中声明) |
format(DateTimeFormatter t) | 格式化本地日期、时间,返回一个字符串 |
parse(Charsequence text) | 将指定格式的字符串解析为日期、时间 |
@Test
public void test7(){
LocalDate now = LocalDate.now();
LocalDate before = now.minusDays(100); // 返回当前时间减去100天的时间对象
System.out.println(before);//2021-07-28
}
@Test
public void test06(){
LocalDate lai = LocalDate.of(2019, 5, 13);
LocalDate go = lai.plusDays(160); // 增加160天
System.out.println(go);//2019-10-20
}
@Test
public void test05(){
LocalDate lai = LocalDate.of(2019, 5, 13);
System.out.println(lai.getDayOfYear()); // 获取当天在年中的天数。133
}
@Test
public void test04(){
LocalDate lai = LocalDate.of(2019, 5, 13);
System.out.println(lai);
}
@Test
public void test03(){
LocalDateTime now = LocalDateTime.now();
System.out.println(now); // 2021-11-05T23:14:32.570
}
@Test
public void test02(){
LocalTime now = LocalTime.now();
System.out.println(now); //23:15:00.857
}
@Test
public void test01(){
LocalDate now = LocalDate.now();
System.out.println(now); //2021-11-05
}
2、指定时区日期时间:ZonedDateTime
常见时区ID:
Asia/Shanghai
UTC
America/New_York
import java.time.ZoneId;
import java.time.ZonedDateTime;
public class TestZonedDateTime {
public static void main(String[] args) {
ZonedDateTime t = ZonedDateTime.now();
System.out.println(t); //2021-11-05T23:16:10.661+08:00[Asia/Shanghai]
ZonedDateTime t1 = ZonedDateTime.now(ZoneId.of("America/New_York"));
System.out.println(t1); // 2021-11-05T11:16:10.662-04:00[America/New_York]
}
}
3、计算日期/时间:Period和Duration
Period:用于计算两个“日期”间隔
public static void main(String[] args) {
LocalDate t1 = LocalDate.now();
LocalDate t2 = LocalDate.of(2018, 12, 31);
Period between = Period.between(t1, t2);
System.out.println(between);
System.out.println("相差的年数:"+between.getYears());//1年
System.out.println("相差的月数:"+between.getMonths());//又7个月
System.out.println("相差的天数:"+between.getDays());//零25天
System.out.println("相差的总数:"+between.toTotalMonths());//总共19个月
}
Duration:用于计算两个“时间”间隔
public static void main(String[] args) {
LocalDateTime t1 = LocalDateTime.now();
LocalDateTime t2 = LocalDateTime.of(2017, 8, 29, 0, 0, 0, 0);
Duration between = Duration.between(t1, t2);
System.out.println(between);
System.out.println("相差的总天数:"+between.toDays());
System.out.println("相差的总小时数:"+between.toHours());
System.out.println("相差的总分钟数:"+between.toMinutes());
System.out.println("相差的总秒数:"+between.getSeconds());
System.out.println("相差的总毫秒数:"+between.toMillis());
System.out.println("相差的总纳秒数:"+between.toNanos());
System.out.println("不够一秒的纳秒数:"+between.getNano());
}
4、DateTimeFormatter:日期时间格式化
该类提供了三种格式化方法:
预定义的标准格式。如:ISO_DATE_TIME;ISO_DATE
本地化相关的格式。如:ofLocalizedDate(FormatStyle.MEDIUM)
自定义的格式。如:ofPattern(“yyyy-MM-dd hh:mm:ss”)
将日期转化为格式化字符串
@Test
public void test10(){
LocalDateTime now = LocalDateTime.now();
// DateTimeFormatter df = DateTimeFormatter.ofLocalizedDateTime(FormatStyle.LONG);//2019年6月6日 下午04时40分03秒
DateTimeFormatter df = DateTimeFormatter.ofLocalizedDateTime(FormatStyle.SHORT);//19-6-6 下午4:40
String str = df.format(now);
System.out.println(str);
}
@Test
public void test9(){
LocalDateTime now = LocalDateTime.now();
DateTimeFormatter df = DateTimeFormatter.ISO_DATE_TIME;//2019-06-06T16:38:23.756
String str = df.format(now);
System.out.println(str);
}
@Test
public void test8(){
LocalDateTime now = LocalDateTime.now();
DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy年MM月dd日 HH时mm分ss秒 SSS毫秒 E 是这一年的D天");
String str = df.format(now);
System.out.println(str); //2021年11月05日 23时20分58秒 075毫秒 星期五 是这一年的309天
}
将格式化的字符串转化为日期对象
@Test
public void test9(){
String str = "2021年11月21日 11时22分33秒";
DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy年MM月dd日 HH时mm分ss秒");
LocalDateTime t1 = LocalDateTime.parse(str, df);
System.out.println(t1); // 2021-11-21T11:22:33
}
3. 基本数据类型对象包装类
基本数据类型,一共有8种. 可以进行计算,但是功能上依然不够用,JDK提供了一套基本数据类型的包装类,功能增强,全部在lang包
基本数据类型 | 对应的包装类 |
---|---|
byte | Byte |
short | Short |
int | Integer |
long | Long |
float | Float |
double | Double |
boolean | Boolean |
char | Character |
基本数据类型的包装类的最重要功能 : 实现类基本数据类型和String的互转
3.1 基本类型int变成Integer类的对象
- Integer类的构造方法
- Integer(int a) int类型转成Integer对象
- Integer(String s)字符串转成Integer对象,字符串必须纯数字格式
- static Integer valueOf(int a) int类型转成Integer对象
- static Integer valueOf(String s) 字符串转成Integer对象,字符串必须纯数字格式
/**
* 创建Integer类的对象
* 构造方法,new
* static方法 valueOf
*/
public static void getInstance(){
Integer i1 = new Integer(100);
Integer i2 = new Integer("120");
System.out.println(i1);
System.out.println(i2);
Integer i3 = Integer.valueOf(200);
Integer i4 = Integer.valueOf("220");
System.out.println(i3);
System.out.println(i4);
}
3.2 String对象转成基本数据类型int
- static int parseInt(String str) 参数字符串转成基本类型,字符串数字格式.
- int intValue() Integer对象构造方法中的字符串,转成基本类型
/**
* 字符串转成基本类型int
* 静态方法parseInt()
* 非静态方法 intValue()
*/
public static void stringToInt(){
int i = Integer.parseInt("100");
System.out.println(i+1);
Integer integer = new Integer("2");
int j = integer.intValue();
System.out.println(j+1);
}
3.3 自动装箱和拆箱
- 自动装箱 : 基本数据类型自动转成引用类型 int -> Integer
- 自动拆箱 : 引用类型自动转成基本数据类型 Integer ->int
public static void auto(){
//自动装箱 int类型自动转成Integer对象
//javac编译特效 Integer integer = Integer.valueOf(1000) 本质还是new Integer
Integer integer = 1000;
System.out.println(integer);
//自动拆箱 Integer类型自动转成int类型
//javac编译特点 integer + 1; integer.intValue()返回int类型 + 1 = 1001
//Integer integer2 = 1001 装箱
Integer integer2 = integer + 1;
System.out.println(integer2);
}
/**
* 自动装箱和拆箱中的问题
*/
public static void auto2(){
Integer i1 = 1000; //new Integer(1000)
Integer i2 = 1000; //new Integer(1000)
System.out.println("i1==i2::" + (i1 == i2) ); // F
System.out.println(i1.equals(i2)); // T
System.out.println("=====忧郁的分割线======");
Integer i3 = new Integer(1);
Integer i4 = new Integer(1);
System.out.println("i3==i4::"+(i3 == i4));// F
System.out.println(i3.equals(i4)); // T
System.out.println("=====忧郁的分割线======");
Integer i5 = 127;
Integer i6 = 127;
System.out.println("i5==i6::"+(i5 == i6)); //true 数据不要超过byte
}