第一篇 - Java之八大基本数据类型与封装类

Java之八大基本数据类型与封装类

基本数据类型介绍

类型分类类型关键词空间大小默认值对应包装类
整数类型byte1个字节0Byte
整数类型short2个字节0Short
整数类型int4个字节0Integer
整数类型long8个字节0Long
字符类型char2个字节‘’(空字符)Character
浮点类型float4个字节0.0Float
浮点类型double8个字节0.0Double
布尔类型boolean1个字节falseBoolean
  • 基本数据类型在对象初始化后都会赋默认值,而包装类在初始化的时候统一赋值为 null

数据类型转换

  • 基本数据类型 按 从“小”到“大” 排序为 (byte,short,char)–int–long–float—double
  • 当两个操作数运算时类型不一致才会进行类型的提升,例如 int a=10; long b =20; long c = a+b; a 为 int ,b为long ,最后相加结果为long
  • 强制转换,隐式转换为从“小”往“大”转,强制转换则为 “大”转“小”。例如 int a = 100; byte b = (byte)a; 但是需要注意的是“大”转“小”,有可能出现精度丢失问题。

常见考点

考点一 整数类型包装类
Integer a = 128;
Integer b = 128;
Integer c = 99;
Integer d = 99;
System.out.println(a==b);// false
System.out.println(c==d);// true
  • 我们如果用反编译工具可以查出 Integer a = 128; 一个语句在编译后 实现的语句为 Integer a = Integer.valueOf(128); 然后可以看一下 这个方法的源码
/**
     * Returns an {@code Integer} instance representing the specified
     * {@code int} value.  If a new {@code Integer} instance is not
     * required, this method should generally be used in preference to
     * the constructor {@link #Integer(int)}, as this method is likely
     * to yield significantly better space and time performance by
     * caching frequently requested values.
     *
     * This method will always cache values in the range -128 to 127,
     * inclusive, and may cache other values outside of this range.
     *
     * @param  i an {@code int} value.
     * @return an {@code Integer} instance representing {@code i}.
     * @since  1.5
     */
public static Integer valueOf(int i) {
	// 默认情况 low为 -128 high 为127
    if (i >= IntegerCache.low && i <= IntegerCache.high)
        return IntegerCache.cache[i + (-IntegerCache.low)];
    return new Integer(i);
}
  • 看此方法的源码以及英文注释已说的很清楚了,会对 -128 至127 数字进行缓存,因此才导致上面的结果。其它的整数类型也同样存在此问题 Byte(all byte values are cached.) Short(This method will always cache values in the range -128 to 127, inclusive, and may cache other values outside of this range.) Long( -128 to 127)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值