Java拾贝第七天——包装类、BigInteger、BigDecimal

发布时间 2023-10-20 11:54:53作者: ocraft

Java拾贝不建议作为0基础学习,都是本人想到什么写什么

基本数据类型怎么变化引用数据类型(对象) Java为每种基本类型都提供了对应的包装类型:

基本数据类型 包装类
int Integer
char Character
short Short
long Long
float Float
double Double
boolean Boolean
byte Byte

因为基本数据类型和包装类一一对应。所以Java提供了转换功能。

即自动装箱和自动拆箱。

自动装,拆箱

public static void main(String[] args) {
int i = 10;//声明一个基本数据类型
Integer integer = new Integer(i);//装箱,将基本数据类型变为包装类
int j = integer.intValue();//拆箱,将包装类变为基本数据类型
}

上述代码为手动装拆箱 下述代码为自动装拆箱

public static void main(String[] args) {
Integer i = 10;
int j = i; }

只是编译阶段的自动装拆箱,其目的是简化代码,运行过程Java自动完整了代码

拆箱可能会NullPointerException

注意!!! 因为是引用类型,不能拿运算符==去进行比较

public static void main(String[] args) {
Integer i=5000;
Integer j=5000;
System.out.println(i==j); }
//false

引用数据类型==比较的是地址值,需equals进行比较内容。

public static void main(String[] args) {
Integer i=5000;
Integer j=5000;
System.out.println(i.equals(j)); }
//true

缓存优化

Java会把小于等于127的Integer转为int。尽管如此引用类型还是要优先使用equals比较。

public static void main(String[] args) {
Integer i=127; Integer j=127;
Integer i1=128; Integer j1=128;
System.out.println(i==j);
System.out.println(i1==j1);
}
/*
true
false
*/

------------恢复内容结束(昨天忘记提交了qwq)------------

BigInteger
BigInteger就是一个可以表示任意大小的整数。(由java提供的一个数学类)

    public static void main(String[] args) {
        long x=12345678910111213141516;//报错,数字过大
        BigInteger integer = new BigInteger("12345678910111213141516");
        BigInteger.valueOf()
        System.out.println(integer);
    }
//12345678910111213141516

由于是引用数据类型,对其进行操作需调用方法

    public static void main(String[] args) {
        BigInteger integer = new BigInteger("12345678910111213141516");
        BigInteger integer2 = new BigInteger("11111111");
        integer.add(integer2);
        System.out.println(integer);
    }
//12345678910111213141516

BigDecimal

有了任意大小的整型,怎么能少了任意大小的浮点型。

BigDecimal就是任意大小的浮点型。

    public static void main(String[] args) {
        BigDecimal d = new BigDecimal("123.55555555555555");
        System.out.println(d);
    }

BigDecimal用scale()方法表示小数位数

    public static void main(String[] args) {
        BigDecimal d = new BigDecimal("123.55555555555555");
        BigDecimal d1 = new BigDecimal("123.5555555");
        BigDecimal d2 = new BigDecimal("123.5");
        BigDecimal d3 = new BigDecimal("123");
        System.out.println(d.scale());
        System.out.println(d1.scale());
        System.out.println(d2.scale());
        System.out.println(d3.scale());
    }
/*
14
7
1
0
*/

比较两个BigDecimal小数位不同会导致结果的不同

    public static void main(String[] args) {
        BigDecimal d = new BigDecimal("123.55");
        BigDecimal d1 = new BigDecimal("123.5500");
        System.out.println(d.equals(d1));
    }
//false

更多方法请自行查询jdk api 1.8