Java的基本类型和包装类

基本类型所占用的字节
  • 1byte = 8bit
  • byte 1个字节
  • short、char 2个字节
  • int、float 4个字节
  • long、double 8个字节
  • boolean 1个字节
java的基本类型
Integer、Short、Byte、Character、Long这几个类的valueOf方法的实现是类似的。

以Integer为例,其valueOf(int i)的源代码为:

public static Integer valueOf(int i) {
        if (i >= IntegerCache.low && i <= IntegerCache.high)
            return IntegerCache.cache[i + (-IntegerCache.low)];
        return new Integer(i);
    }

在Integer里面IntegerCache.low是固定的-128,IntegerCache.high默认是127,但是也可以通过-XX:AutoBoxCacheMax=<size>来配置,而Short、Byte、Character、Long的缓存大小都是固定在-128~127的。

Double、Float的valueOf方法也是类似的。

以Double 为例,其valueOf(double d)的源代码为:

public static Double valueOf(double d) {
        return new Double(d);
    }

Double的valueOf方法每次返回的都是新的对象。

Boolean的valueOf方法比较特殊。
    /**
     * The {@code Boolean} object corresponding to the primitive
     * value {@code true}.
     */
    public static final Boolean TRUE = new Boolean(true);

    /**
     * The {@code Boolean} object corresponding to the primitive
     * value {@code false}.
     */
    public static final Boolean FALSE = new Boolean(false);

    public static Boolean valueOf(boolean b) {
        return (b ? TRUE : FALSE);
    }

Boolean因为只有true和false两种情况,所以在加载的时候就会创建TRUE和FALSE两个对象。自动装箱的时候则返回这两个对象的其中一个。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容