8. Java常用类
8.1 字符串相关的类
-
String的特性:
-
Java 程序中的所有字符串字面值(如 “abc” )都作为此类的实例实现
-
是一个final类,代表不可变的字符序列,不可被继承
-
String实现了
java.io.Serializable
接口,表示字符串可以序列化 -
String实现了
Comparable<String>
接口,表示字符串可以比较大小 -
String内部定义了
final byte[] value;
用与存储字符串数据public final class String implements java.io.Serializable, Comparable<String>, CharSequence, Constable, ConstantDesc { @Stable private final byte[] value; }
-
String代表一个不可变的字符序列,简称:不可变性:只要需要修改,就一定会重新造
-
当对字符串重新赋值时,需要重写指定内存区域赋值,不能使用原有的value进行赋值。通过字面量的方式(区别于new)给一个字符串赋值,此时的字符串值声明在字符串常量池中(字符串常量池中是不会存储相同内容的字符串的)
首先判断常量池里是否有"abc"或"hello",如果没有创建一个常量;如果有直接指向
-
当对现有的字符串进行连接操作时,也需要重新指定内存区域赋值,不能使用原有的value赋值
String s2 = "abc"; String s3 = s2 + "def"; System.out.println(s3);//abcdef System.out.println(s2);//abc——s2不会改变
-
当调用String的replace( )方法修改字符串的指定字符时,也需要重新指定内存区域赋值
String s5 = s2.replace('a','m'); System.out.println(s2);//abc——s2不会改变 System.out.println(s5);//mbc
-
-
-
String的赋值方式:
-
字面量赋值:
String str = "abc";
-
String对象的创建:String的构造器
String() //初始化一个新创建的 String 对象,使其表示一个空字符序列。 String(char[] value) //分配一个新的 String,使其表示字符数组参数中当前包含的字符序列。 String(char[] value, int offset, int count) //分配一个新的 String,它包含取自字符数组参数一个子数组的字符。 String(String original) //初始化一个新创建的 String 对象,使其表示一个与参数相同的字符序列;换句话说,新创建的字符串是该参数字符串的副本。 String(StringBuffer buffer) //分配一个新的字符串,它包含字符串缓冲区参数中当前包含的字符序列。
-
两种方式的区别:
//通过字面量定义的方式: //此时s1和s2的数据abc声明在方法区中的字符串常量池中 String s1 = "abc"; String s2 = "abc"; //通过new构造器的方式: //此时s3和s4保存的地址值,是数据在堆空间中开辟的空间地址 String s3 = new String("abc"); String s4 = new String("abc"); System.out.println(s1 == s2); System.out.println(s3 == s4);
-
面试题一:
Perdon p1 = new Person("Tom",12); Perdon p2 = new Person("Tom",12); System.out.println(p1.name == p2.name);//true p1.name = "Jack"; System.out.println(p2.name);//Tom
-
面试题二:
String s = new String("abc");//在内存中创建了几个数组? //两个,一个是对空间中new的结构,另一个是char[]对应的常量池中的数据"abc"
-
-
String的拼接操作:
-
-
结论:
- 常量与常量(字面量赋值或final修饰)的拼接结果在常量池。 且常量池中不会存在相同内容的常量
- 只要其中有一个是变量, 结果就在堆中
- 如果拼接的结果调用intern()方法, 返回值就在常量池中
-
-
String的常用方法:
-
int length()
返回字符串的长度String s1 = "helloworld"; System.out.println(s1.length());//10
-
char charAt(int index)
返回某索引处的字符System.out.println(s1.charAt(2));//l
-
boolean isEmpty()
判断是否是空字符串System.out.println(s1.isEmpty());//false
-
String toLowerCase() String toUpperCase()
将 String 中的所有字符转换为大、小写String s2 = s1.toLowerCase(); String s5 = s1.toUpperCase(Locale.ROOT); System.out.println(s2);//helloworld System.out.println(s1);//helloworld
-
String trim()
返回字符串的副本, 忽略前导空白和尾部空白String s3 = " hello world "; String s4 = s3.trim(); System.out.println(s4);//hello world
-
boolean equals(Object obj)
比较字符串的内容是否相同System.out.println(s1.equals(s4));//false
-
boolean equalsIgnoreCase(String anotherString)
与equals方法类似, 忽略大小写System.out.println(s1.equalsIgnoreCase(s5));//t
-
String concat(String str)
将指定字符串连接到此字符串的结尾。 等价于用“+”String s6 = s3.concat("def"); System.out.println(s6);// hello world def
-
int compareTo(String anotherString)
比较两个字符串的大小String s7 = "abc"; String s8 = "abd"; System.out.println(s7.compareTo(s8));//-1
-
String substring(int beginIndex)
返回一个新的字符串, 它是此字符串的从beginIndex开始截取到最后的一个子字符串String s9 = s2.substring(2); System.out.println(s9);//lloworld
-
String substring(int beginIndex, int endIndex)
返回一个新字符串, 它是此字符串从beginIndex开始截取到endIndex(不包含)的一个子字符串)String s10 = s2.substring(2,4); System.out.println(s10);//ll
-
boolean endsWith(String suffix
测试此字符串是否以指定的后缀结束System.out.println(s1.endsWith("ld"));//true
-
boolean startsWith(String prefix)
测试此字符串是否以指定的前缀开始System.out.println(s1.startsWith("he"));//true System.out.println(s1.startsWith("HE"));//false
-
boolean startsWith(String prefix, int toffset)
测试此字符串从指定索引开始的子字符串是否以指定前缀开始System.out.println(s1.startsWith("he",0));//true
-
boolean contains(CharSequence s)
当且仅当此字符串包含指定的 char 值序列时,返回 true -
int indexOf(String str)
返回指定子字符串在此字符串中第一次出现处的索引 -
int indexOf(String str, int fromIndex)
返回指定子字符串在此字符串中第一次出现处的索引,从指定的索引开始 -
int lastIndexOf(String str)
返回指定子字符串在此字符串中最后一次出现处的索引 -
int lastIndexOf(String str, int fromIndex)
返回指定子字符串在此字符串中最后一次出现处的索引,从指定的索引开始反向搜索
注: indexOf和lastIndexOf方法如果未找到都是返回-1 -
String replace(char oldChar, char newChar)
返回一个新的字符串, 它是通过用 newChar 替换此字符串中出现的所有 oldChar 得到的 -
String replace(CharSequence target, CharSequence replacement)
测使用指定的字面值替换序列替换此字符串所有匹配字面值目标序列的子字符串 -
String replaceAll(String regex, String replacement)
使用给定的replacement替换此字符串所有匹配给定的正则表达式的子字符串String str = "12hello34world5java7891mysql456"; //把字符串中的数字(d)替换成","",如果结果中开头和结尾有","的话去掉 String string = str.replaceAll("\\d+", ",").replaceAll("^,|,$", ""); System.out.println(string);
-
String replaceFirst(String regex, String replacement)
使用给定的replacement替换此字符串匹配给定的正则表达式的第一个子字符串 -
boolean matches(String regex)
告知此字符串是否匹配给定的正则表达式String str = "12345"; //判断str字符串中是否全部有数字组成,即有1-n个数字组成 boolean matches = str.matches("\\d+"); System.out.println(matches); String tel = "0571-4534289"; //判断这是否是一个杭州的固定电话 boolean result = tel.matches("0571-\\d{7,8}"); System.out.println(result);
-
String[] split(String regex)
根据给定正则表达式的匹配拆分此字符串String str = "hello|world|java"; String[] strs = str.split("\\|"); //以"|"切分 for (int i = 0; i < strs.length; i++) { System.out.println(strs[i]); } System.out.println();
-
String[] split(String regex, int limit)
根据匹配给定的正则表达式来拆分此字符串, 最多不超过limit个, 如果超过了, 剩下的全部都放到最后一个元素中
-
-
String与其他结构之间的转换:
- 字符串
→
\to
→基本数据类型、包装类:调用包装类的静态方法:
parseXxx( )
- 基本数据类型、包装类
→
\to
→字符串:调用String重载的
valueOf( )
- 字符数组
→
\to
→字符串:调用String的构造器
new String(arr)
- 字符串
→
\to
→字符数组:调用String的
toCharArray( )
- **字节(二进制)数组
→
\to
→字符串:**调用String的构造器
new String(bytes)
- 字符串
→
\to
→字节数组:调用String的
getBytes( )
- 字符串
→
\to
→基本数据类型、包装类:调用包装类的静态方法:
-
关于StringBuffer和StringBuilder的使用
-
三者区别:
- String:不可变的字符序列;底层使用char[ ]存储
- StringBuffer:可变字符序列;线程安全的,效率偏低;底层使用char[ ]存储
- StringBuilder:可变字符序列;jdk5.0新增,线程不安全的,效率高;底层使用char[ ]存储
-
源码分析:
String str = new String(); //底层:char[] value = new char[0] String str1 = new String("abc"); //char[] value = new char[]{'a','b','c'} StringBuffer sb1 =new StringBuffer(); //char[] value = new char[16]; //底层创建了一个长度为16的char[] System.out.println(sb1.length()); sb1.append('a');//value[0] = 'a'; sb1.append('b');//value[1] = 'b'; StringBuffer sb2 = new StringBuffer("abc"); //char[] value = new char["abc".length() +16];
-
扩容问题:
如果要添加的数据底层数组放不下了,那就需要扩容底层数组,默认情况下,扩容为原来的2倍+2,同时将原有数组中的元素复制到新的数组中
-
指导意义:
开发中使用
StringBuffer(int capacity)
或StringBuilder(int capacity)
-
使用:(StringBuffer和StringBuilder基本相同)
-
构造器
-
StringBuffer():初始容量为16的字符串缓冲区
-
StringBuffer(int size):构造指定容量的字符串缓冲区
-
StringBuffer(String str):将内容初始化为指定字符串内容
//不可变 String s = new String("我喜欢学习"); //可变 StringBuffer buffer = new StringBuffer("我喜欢学习"); buffer.append("数学");
-
-
常用方法
append(xxx)
:提供了很多的append()方法, 用于进行字符串拼接delete(int start,int end)
:删除指定位置的内容replace(int start, int end, String str)
:把[start,end)位置替换为strinsert(int offset, xxx)
:在指定位置插入xxxreverse()
:把当前字符序列逆转int indexOf(String str)
:返回第一个出现的位置String substring(int start,int end)
:返回指定范围的子串int length()
:返回长度char charAt(int n )
:返回指定字符的位置void setCharAt(int n ,char ch)
:将指定位置的字符改为新的
-
-
效率对比:StringBuilder > StringBuffer > String
-
8.2 JDK 8之前的日期时间API
-
java.lang.System类
-
System类提供的public static long
currentTimeMillis( )
用来返回当前时间与1970年1月1日0时0分0秒之间以毫秒为单位的时间差 -
long time = System.currentTimeMillis(); System.out.println(time);//1622513200505(时间戳)
-
-
java.util.Date类
-
表示特定的瞬间,精确到毫秒
-
构造器:
-
Date()
: 使用无参构造器创建的对象可以获取本地当前时间 -
Date(long date)
Date date = new Date(1622513500124L);
-
-
常用方法:
-
getTime()
:返回自 1970 年 1 月 1 日 00:00:00 GMT 以来此 Date 对象
表示的毫秒数Date date = new Date(); System.out.println(date.getTime());//1622513500124
-
toString()
:把此 Date 对象转换为以下形式的 String: dow mon ddhh:mm:ss zzz yyyy 其中: dow 是一周中的某一天 (Sun, Mon, Tue,Wed, Thu, Fri, Sat), zzz是时间标准Date date = new Date(); System.out.println(date.toString());//Tue Jun 01 10:10:46 CST 2021
-
其它很多方法都过时了
-
-
java.sql.Date对应着数据库中的日期类型的变量
-
如何实例化:
java.sql.Date date = new java.sql.Date(1622513500124L); System.out.println(date);//2021-06-01
-
java.util.Date对象如何转化为java.sql.Date对象
Date date1 = new Date(); java.sql.Date date2 = new java.sql.Date(date1.getTime()); System.out.println(date2);//2021-06-01
-
-
-
java.text.SimpleDateFormat类
-
一个不与语言环境有关的方式来格式化和解析日期的具体类,允许进行
- 格式化:日期 → \to →指定字符串
- 解析:字符串 → \to →日期
-
格式化:
sdf.format(date)
//1.使用默认构造器SimpleDateFormat sdf = new SimpleDateFormat();Date date = new Date();System.out.println(date);//Tue Jun 01 10:49:27 CST 2021String format = sdf.format(date);System.out.println(format);//2021/6/1 上午11:13//2.使用带参数的构造器SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss"); //指定格式Date date1 = new Date();String format1 = sdf1.format(date1);System.out.println(format1);//2021-06-01 12:01:11
-
解析:
sdf.parse( )
//String str = "2019-08-09"; //识别不了会报异常:ParseException String str = "2021/6/1 上午11:57"; //要符合格式 Date parse = sdf.parse(str); System.out.println(parse);
-
-
java.util.Calendar(日历)类
-
抽象基类,用于完成日期字段之间相互操作的功能
-
实例化:
-
方式一:创建其子类(GregorianCalendar)的对象
-
方式二:调用其静态方法:
getInstance()
Calendar calendar = Calendar.getInstance();
-
-
常用方法:
-
get()
Calendar calendar = Calendar.getInstance(); int i = calendar.get(Calendar.DAY_OF_MONTH); System.out.println(i);//1 int i1 = calendar.get(Calendar.DAY_OF_YEAR); System.out.println(i1);//152
-
set()
calendar.set(Calendar.DAY_OF_MONTH,22); int i2 = calendar.get(Calendar.DAY_OF_MONTH); System.out.println(i2);//22
-
add()
calendar.add(Calendar.DAY_OF_MONTH,3); //calendar.add(Calendar.DAY_OF_MONTH,-3); int i3 = calendar.get(Calendar.DAY_OF_MONTH); System.out.println(i3);//25
-
getTime()
日历类 → \to →DateDate time = calendar.getTime(); System.out.println(time);//修改后的Fri Jun 25 12:17:19 CST 2021
-
setTime()
Date → \to →日历类Date date1 = new Date(); calendar.setTime(date1); int i4 = calendar.get(Calendar.DAY_OF_MONTH); System.out.println(i4);//1:重新设置回来了
-
-
8.3 JDK 8中新的日期时间API
JDK 1.0中包含了一个java.util.Date类,但是它的大多数方法已经在JDK 1.1引入Calendar类之后被弃用了。而Calendar并不比Date好多少。它们面临的问题是:
- 可变性:像日期和时间这样的类应该是不可变的
- 偏移性: Date中的年份是从1900开始的,而月份都从0开始
- 格式化:格式化只对Date有用, Calendar则不行
- 此外,它们也不是线程安全的;不能处理闰秒等
Java 8 吸收了 Joda-Time 的精华,以一个新的开始为 Java 创建优秀的 API
java.time
–包含值对象的基础包java.time.format
– 格式化和解析时间和日期
-
java.time中的类:
- LocalDate:代表IOS格式(yyyy-MM-dd)的日期,可以存储 生日、纪念日等日期
- LocalTime:表示一个时间,而不是日期
- LocalDateTime:用来表示日期和时间
-
方法:
-
now()
:静态方法, 根据当前时间创建对象/指定时区的对象LocalDate localDate = LocalDate.now(); LocalTime localTime = LocalTime.now(); LocalDateTime localDateTime = LocalDateTime.now(); System.out.println(localDate);//2021-06-01 System.out.println(localTime);//12:57:33.350232500 System.out.println(localDateTime);//2021-06-01T12:57:33.350232500
-
of()
:静态方法, 根据指定日期/时间创建对象(不用再考虑偏移量了)LocalDate localDate = LocalDate.of(2021,6,1); System.out.println(localDate);//2021-06-01
-
getDayOfMonth() / getDayOfYear() / getDayOfWeek()
:当月、年、周的第几天 -
getMonth()
:获得月份, 返回一个 Month 枚举值 -
getMonthValue() / getYear()
:获得月份(1-12) 、获得年份 -
getHour()/getMinute()/getSecond()
:获得当前对象对应的小时、 分钟、 秒 -
withDayOfMonth() / withDayOfYear() / withMonth()/withYear()
:将月份天数、 年份天数、 月份、 年份修改为指定的值并返回新的对象(不需考虑偏移量)LocalDateTime localDateTime = LocalDateTime.now(); LocalDateTime localDateTime1 = localDateTime.withDayOfMonth(22); LocalDateTime localDateTime2 = localDateTime1.withHour(4); //又不可变性 System.out.println(localDateTime);//2021-06-01T16:04:28.832504400 System.out.println(localDateTime1);//2021-06-22T16:04:28.832504400 System.out.println(localDateTime2);//2021-06-22T04:04:28.832504400
-
plusDays(), plusWeeks(), plusMonths(), plusYears(),plusHours()
:向当前对象添加几天、 几周、 几个月、 几年、 几小时 -
minusMonths() / minusWeeks()/ minusDays()/minusYears()/minusHours()
:从当前对象减去几月、 几周、 几天、 几年、 几小时
-
-
instant类
-
时间线上的一个瞬时点
-
方法:
-
now()
:静态方法, 返回默认UTC格林威治时区的Instant类的对象 -
ofEpochMilli(long epochMilli)
:静态方法 数之后的,Instant 返回在类的对象 1970-01-01 00:00:00基础上加上指定毫秒 -
atOffset(ZoneOffset offset)
:结合即时的偏移来创建一个 OffsetDateTime -
toEpochMilli()
:返回1970-01-01 00:00:00到当前时间的毫秒数, 即为时间戳//实例化 Instant instant = Instant.now(); System.out.println(instant);//格林威治时间 //调整偏移量 OffsetDateTime offsetDateTime = instant.atOffset(ZoneOffset.ofHours(8)); System.out.println(offsetDateTime); //计算instant的时间戳 long l = instant.toEpochMilli(); System.out.println(l); //用时间戳找instant实例 Instant instant1 = Instant.ofEpochMilli(1622535397734L); System.out.println(instant1);
-
-
-
java.time.format.DateTimeFormatter类
-
该类提供了三种格式化方法
-
预定义的标准格式
DateTimeFormatter formatter = DateTimeFormatter.ISO_LOCAL_DATE_TIME; //格式化:日期-->字符串 LocalDateTime localDateTime = LocalDateTime.now(); String format = formatter.format(localDateTime); System.out.println(format);//2021-06-01T16:22:10.8436232 //解析:字符串-->日期 TemporalAccessor parse = formatter.parse("2021-06-01T16:22:10.8436232"); System.out.println(parse);//{},ISO resolved to 2021-06-01T16:22:10.843623200
-
本地化相关的格式
-
⭐自定义的格式
//格式化: DateTimeFormatter timeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd hh:mm:ss"); String format = timeFormatter.format(LocalDateTime.now()); System.out.println(format);//2021-06-01 05:14:54 //解析: TemporalAccessor parse = timeFormatter.parse("2021-06-01 05:14:54"); System.out.println(parse); //{NanoOfSecond=0, MicroOfSecond=0, SecondOfMinute=54, HourOfAmPm=5, MinuteOfHour=14, MilliOfSecond=0},ISO resolved to 2021-06-01
-
-
8.4 Java比较器
在Java中经常会涉及到对象数组的排序问题,那么就涉及到对象之间的比较问题
-
Java实现对象排序的方式有两种:
- 自然排序:
java.lang.Comparable
,一旦指定一劳永逸 - 定制排序:
java.util.Comparator
,临时性的给定比较规则
- 自然排序:
-
自然排序:java.lang.Comparable
-
像String、包装类等实现了Comparable接口,重写了compareTo()方法,给出了比较两个对象大小的方式
String[] arr = new String[]{"AA","BB","EE","DD"}; Arrays.sort(arr);//从小到大排的 System.out.println(Arrays.toString(arr));//[AA, BB, DD, EE]
-
重写
compareTo()
方法的规则:- 如果当前对象this大于形参对象obj, 则返回正整数
- 如果当前对象this小于形参对象obj, 则返回负整数
- 如果当前对象this等于形参对象obj, 则返回零
-
对于自定义类,如果需要排序,可以让自定义类实现Comparable接口,重写compareTo()方法
public class Goods implements Comparable{//⭐实现接口 private String name; private int price; /*get、set、构造器、toString*/ //⭐指明排序方式 @Override public int compareTo(Object o) { if(o instanceof Goods){ Goods goods = (Goods) o; if(this.price > goods.price){ return 1; }else if(this.price < goods.price){ return -1; }else { //若价格相同,则比名字,再嵌套一个compareTo() //name是String类型的,已经有重写好的了 //返回-负的实现从高到低 return -this.name.compareTo(goods.name); } } throw new RuntimeException("传入的数据类型不一致"); }
public class Test { public static void main(String[] args) throws ParseException { Goods[] goods = new Goods[4]; goods[0]=new Goods("lenovo",34); goods[1]=new Goods("huawei",22); goods[2]=new Goods("xiaomi",3); goods[3]=new Goods("dell",56); Arrays.sort(goods); System.out.println(Arrays.toString(goods)); //[Goods{name='xiaomi', price=3}, Goods{name='huawei', price=22}, Goods{name='lenovo', price=34}, Goods{name='dell', price=56}] } }
-
-
定制排序:java.util.Comparator
-
当元素的类型没有实现java.lang.Comparable接口而又不方便修改代码,或者实现了java.lang.Comparable接口的排序规则不适合当前的操作,那么可以考虑使用 Comparator 的对象来排序
-
重写
compare(Object o1,Object o2)
方法的规则:- 如果方法返回正整数,则表示o1大于o2
- 如果返回0,表示相等
- 返回负整数,表示o1小于o2
-
public class StringTest { public static void main(String[] args) throws ParseException { Goods[] goods = new Goods[4]; goods[0]=new Goods("lenovo",34); goods[1]=new Goods("huawei",22); goods[2]=new Goods("xiaomi",3); goods[3]=new Goods("dell",56); //⭐要排序时,临时给一个排序方法 //匿名类实现接口Comparator,重写compare() Arrays.sort(goods, new Comparator<Goods>() { @Override public int compare(Goods o1, Goods o2) { if(o1.getPrice() > o2.getPrice()){ return 1; }if(o1.getPrice() < o2.getPrice()){ return -1; }else{ return o1.getName().compareTo(o2.getName()); } } }); System.out.println(Arrays.toString(goods)); } }
-
8.5 System类
-
代表系统,系统级的很多属性和控制方法都放置在该类的内部。该类位于java.lang包
-
由于该类的构造器是private的,所以无法创建该类的对象,也就是无法实例化该类。其内部的成员变量和成员方法都是static的, 所以也可以很方便的进行调用
-
成员变量:System类内部包含
in
、out
和err
三个成员变量,分别代表标准输入流(键盘输入),标准输出流(显示器)和标准错误输出流(显示器) -
成员方法:
-
native long currentTimeMillis()
:该方法的作用是返回当前的计算机时间,时间的表达格式为当前计算机时间和GMT时间(格林威治时间)1970年1月1号0时0分0秒所差的毫秒数。 -
void exit(int status)
:该方法的作用是退出程序。其中status的值为0代表正常退出,非零代表
异常退出。 使用该方法可以在图形界面编程中实现程序的退出功能等。 -
void gc()
:该方法的作用是请求系统进行垃圾回收。至于系统是否立刻回收,则取决于系统中垃圾回收算法的实现以及系统执行时的情况 -
String getProperty(String key)
:该方法的作用是获得系统中属性名为key的属性对应的值。系统中常见的属性名以及属性的作用如下表所示:String javaVersion = System.getProperty("java.version"); System.out.println("java的version:" + javaVersion); String javaHome = System.getProperty("java.home"); System.out.println("java的home:" + javaHome); String osName = System.getProperty("os.name"); System.out.println("os的name:" + osName); String osVersion = System.getProperty("os.version"); System.out.println("os的version:" + osVersion); String userName = System.getProperty("user.name"); System.out.println("user的name:" + userName); String userHome = System.getProperty("user.home"); System.out.println("user的home:" + userHome); String userDir = System.getProperty("user.dir"); System.out.println("user的dir:" + userDir);
-
8.6 Math类
-
java.lang.Math提供了一系列静态方法用于科学计算。其方法的参数和返回值类型一般为double型
-
abs 绝对值 acos,asin,atan,cos,sin,tan 三角函数 sqrt 平方根 pow(double a,doble b) a的b次幂 log 自然对数 exp e为底指数 max(double a,double b) min(double a,double b) random() 返回0.0到1.0的随机数 long round(double a) double型数据a转换为long型(四舍五入) toDegrees(double angrad) 弧度—>角度 toRadians(double angdeg) 角度—>弧度
8.2 BigInteger和BigDecimal
-
BigInteger
- Integer类作为int的包装类,能存储的最大整型值为 2 31 − 1 2^{31}-1 231−1, Long类也是有限的,最大为 2 63 − 1 2^{63}-1 263−1
- BigInteger可以表示不可变的任意精度的整数
- 构造器:BigInteger(String val): 根据字符串构建BigInteger对象
-
BigDecimal
- 商业计算中,要求数字精度比较高,故用到java.math.BigDecimal类
- 构造器
- public BigDecimal(double val)
- public BigDecimal(String val)
- 常用方法
- public BigDecimal add(BigDecimal augend)
- public BigDecimal subtract(BigDecimal subtrahend)
- public BigDecimal multiply(BigDecimal multiplicand)
- public BigDecimal divide(BigDecimal divisor, int scale, int roundingMode)
-
示例:
BigInteger bi = new BigInteger("12433241123"); BigDecimal bd = new BigDecimal("12435.351"); BigDecimal bd2 = new BigDecimal("11"); //很大的一个数 System.out.println(bi); //bd除以bd2,默认 System.out.println(bd.divide(bd2, BigDecimal.ROUND_HALF_UP)); //bd除以bd2,保留15位小数 System.out.println(bd.divide(bd2, 15, BigDecimal.ROUND_HALF_UP))