JAVA数据类型

2018-09-27  本文已影响0人  Jasonlulu

1.1 数据类型

1.1.1 内置数据类型

整形:用于表示没有小数部分的数值

Java一共定义了4种整形类型。

int
long:
short
byte:

浮点类型:用于表示有小数部分的数值

Java一共定义了2种浮点类型。

float
double

其中,命令sout输出2.0-1.1将打印出0.899999999999而不是0.9如下图


浮点数不适合用于无法接受四舍五入的金融中,如上图所示

其余两种类型

char

Eg:char letter = 'A';char m='中'+1;

char
boolean

1.2.1 引用数据类型

除了以上八种基本类型,其余的都是对象,包括数组

包装类型

包装类的用途

自动装箱和自动拆箱(在JDK1.5以后加入)

自动装箱:

基本类型自动的封装到了与它相同的类型的包装中

    Integer a=5; 
 // 编译器执行了Integer a = Integer.valueOf(5)

valueO源代码:

 public static Integer valueOf(int i) {
        if (i >= IntegerCache.low && i <= IntegerCache.high)
            return IntegerCache.cache[i + (-IntegerCache.low)];
        return new Integer(i);
    }
自动拆箱:
    int b=a;
 //自动拆箱,实际上执行了 int b = a.intValue()
public class wrapClass {
    public static void main(String[] args) {
        Integer b=null;
        int a=b;//会报错
    }
}

报错如图:


image.png

错误的原因是因为默认调用了b.intValue(),所以报出空指针异常。

缓存的问题

在其中有一个有趣的现象

 public static void main(String[] args) {
        Integer a1=1128;
        Integer a2=1128;
        System.out.println(a1==a2);
        System.out.println("##############");
        Integer b1=-128;
        Integer b2=-128;
        System.out.println(b1==b2);
    }

结果如下图:


缓存结果

各个包装类缓存值范围 :

原因是因为在[-128,127]之间的数据还是会被当成基本数据来看。

上一篇 下一篇

猜你喜欢

热点阅读