趣谈,JAVA数据类型,取值范围,判断溢出。

整型:

byte:-2^7 ~ 2^7-1,即-128 ~ 127。1字节。Byte。末尾加B

short:-2^15 ~ 2^15-1,即-32768 ~ 32767。2字节。Short。末尾加S

有符号int:-2^31 ~ 2^31-1,即-2147483648 ~ 2147483647。4字节。Integer。

无符号int:0~2^32-1。

long:-2^63 ~ 2^63-1,即-9223372036854774808 ~ 9223372036854774807。8字节。Long。末尾加L。(也可以不加L)
浮点型:

float:4字节。Float。末尾加F。(也可以不加F)

double:8字节。Double。

字符型:

char:2字节。Character。

布尔型:

boolean:Boolean。
类型转换:

boolean类型与其他基本类型不能进行类型的转换(既不能进行自动类型的提升,也不能强制类型转换), 否则,将编译出错。
在这里插入图片描述byte型不能自动类型提升到char,char和short直接也不会发生自动类型提升(因为负数的问题),同时,byte当然可以直接提升到short型。
判断溢出
加法

public static int addExact(int x, int y) {
        int r = x + y;
        // HD 2-12 Overflow iff both arguments have the opposite sign of the result
        if (((x ^ r) & (y ^ r)) < 0) {
            throw new ArithmeticException("integer overflow");
        }
        return r;
    }

减法

 public static int subtractExact(int x, int y) {
        int r = x - y;
        // HD 2-12 Overflow iff the arguments have different signs and
        // the sign of the result is different than the sign of x
        if (((x ^ y) & (x ^ r)) < 0) {
            throw new ArithmeticException("integer overflow");
        }
        return r;
    }

乘法

public static int multiplyExact(int x, int y) {
        long r = (long)x * (long)y;
        if ((int)r != r) {
            throw new ArithmeticException("integer overflow");
        }
        return (int)r;
    }

注意 long和int是不一样的

 public static long multiplyExact(long x, long y) {
        long r = x * y;
        long ax = Math.abs(x);
        long ay = Math.abs(y);
        if (((ax | ay) >>> 31 != 0)) {
            // Some bits greater than 2^31 that might cause overflow
            // Check the result using the divide operator
            // and check for the special case of Long.MIN_VALUE * -1
           if (((y != 0) && (r / y != x)) ||
               (x == Long.MIN_VALUE && y == -1)) {
                throw new ArithmeticException("long overflow");
            }
        }
        return r;
    }

参考自:https://blog.csdn.net/qq_33330687/article/details/81626157
https://www.cnblogs.com/cing/p/8038055.html

发布了20 篇原创文章 · 获赞 17 · 访问量 1799

猜你喜欢

转载自blog.csdn.net/qq_42534991/article/details/103985565
今日推荐