Java类型:基本与包装类型、String

八大基础类型(都有对应的包装类型):

整数:byte(1字节)、short(2字节)、int(4字节)、long(8字节)
浮点数:float(4 byte)、double(8 byte)
字符型:char(2 byte)
布尔型:boolean(1 byte)

基本类型byteshortintlong
位数8位16位32位64位
容量255655354*10918*1018
表示范围-128~127-32768~327672*1099*1018

两者的区别

1. 包装类型 可以 为null,但基本类型 不可以 为null
阿里巴巴Java开发手册:
    数据库的查询结果可能为null,如果POJO的属性使用基本类型,会发生自动拆箱行为(比如把Integer转换为int),就会发生NullPointerException异常,故POJO的属性必须使用包装类型。

2. 包装类型 可用于 泛型,但基本类型不可以
例如:

List<int> list=null;//错误
List<Integer> list1=null;//正确

  Java是一个面向对象的编程语言,但基本类型不具备对象的性质,故需要包装类型将其包装为对象,才能在Collection中使用。

3. 包装类型的效率比基本类型低
从内存使用情况看:
每一个方法都有一个栈,且对应一个栈帧,方法中的基本数据类型变量直接在栈帧中分配。如果是static、final类型的基本数据类型则存储在运行时常量池中,和String一样。
包装类型变量属于引用型变量,在虚拟机栈中存储引用,在堆中存储具体的对象,对象类型数据(Class等信息)存储在方法区中。
参考生成对象时的内存情况

自动拆/装箱:

		Integer a = 127;//自动装箱,是通过Integer.valueOf()完成的
        Integer aa=new Integer(127);//手动装箱
        int aaa=aa;//自动拆箱,是通Integer.intValue()完成的
        int aaaa=aa.intValue();//手动拆箱

关于IntegerCache:

IntegerCache 是 Integer 中一个私有静态内部类,设计该类的目的是,不用反复 new 值相同的 Integer 对象,减少了内存占用,提高常用小数值的效率。
可以在如下的源码中看到,IntegerCache 中的 low 是-128,但 high 是可以通过启动参数修改的。

    /**
     * Cache to support the object identity semantics of autoboxing for values between
     * -128 and 127 (inclusive) as required by JLS.
     *
     * The cache is initialized on first usage.  The size of the cache
     * may be controlled by the {@code -XX:AutoBoxCacheMax=<size>} option.
     * During VM initialization, java.lang.Integer.IntegerCache.high property
     * may be set and saved in the private system properties in the
     * sun.misc.VM class.
     */

    private static class IntegerCache {
        static final int low = -128;
        static final int high;
        static final Integer cache[];

        static {
            // high value may be configured by property
            int h = 127;
            String integerCacheHighPropValue =
                sun.misc.VM.getSavedProperty("java.lang.Integer.IntegerCache.high");
            if (integerCacheHighPropValue != null) {
                try {
                    int i = parseInt(integerCacheHighPropValue);
                    i = Math.max(i, 127);
                    // Maximum array size is Integer.MAX_VALUE
                    h = Math.min(i, Integer.MAX_VALUE - (-low) -1);
                } catch( NumberFormatException nfe) {
                    // If the property cannot be parsed into an int, ignore it.
                }
            }
            high = h;

            cache = new Integer[(high - low) + 1];
            int j = low;
            for(int k = 0; k < cache.length; k++)
                cache[k] = new Integer(j++);

            // range [-128, 127] must be interned (JLS7 5.1.7)
            assert IntegerCache.high >= 127;
        }
        private IntegerCache() {}
    }

关于IntegerCache带来的数值对比问题

@Test
    public void testEquals() {
        int a1 = 128;
        int a2 = 128;
        System.out.println(a1 == a2);//true,基本类型存储在虚拟机栈中,而==比较虚拟机栈中的地址,则可以达到目的

        Integer b1 = 127;
        int b2 = 127;
        Integer b3=127;
        System.out.println(b1 == b2);//true
        System.out.println(b1==b3);//true,当包装类型的值在-128-127之间,会使用到IntegerCache,相当于使用了栈中的数据,而==比较的是栈中的地址

		b1 = new Integer(127);
        b3 = new Integer(127);
        System.out.println(b1 == b3);//false,此处是对象,在栈中的地址指向不同的堆对象。
		
        Integer c1=128;
        Integer c2=128;
        System.out.println(c1==c2);//false
        System.out.println(c1.equals(c2));//true
    }

是否只有Integer才有缓冲区?

不是。八大基础类型和 String ,这些类型为了使他们在运行过程中速度更快,更节省内存,都提供了一种常量池。

缓冲区域:

  • boolean values true and false
  • all byte values
  • short values between -128 and 127
  • char in the range \u0000 to \u007F

String、StringBuilder、StringBuffer

1. String 字符串常量

   String 是不可变的对象, 每次对 String 值的改变,都会生成一个新String 对象。所以适合字符串对象不常改变的情况下使用

   Java中的字符常量都是使用UTF8编码的,UTF8编码使用1~4个字节来表示具体的Unicode字符。

长度限制

String 也是有长度限制,分为两个方向的限制:

1. 编译期间限制为 65535 字节

Javac编译器限制长度为 65535 字节,一般中文占用 2 个字节,数字字母为 1字节

2. 运行期间的限制

最大长度为 Integer.MAX_VALUE,大约需要 4GB 的内存才能存储最大长度的字符串,同时,需要注意虚拟机对常量池分配的内存限制

2. StringBuffer 字符串变量(线程安全)

在字符串缓冲区中对对象本身进行操作,使用了synchronized,适合字符串对象经常改变或多线程的情况下使用

3. StringBuilder 字符串变量(非线程安全)

在字符串缓冲区中对对象本身进行操作,适合字符串对象经常改变或单线程的情况下使用

效率:String > StringBuilder > StringBuffer


关于 String与String#intern() 的解析(在JDK 7/8的环境)

String s1 = "hello world";
String s2 = "hello world";
System.out.println(s1 == s2);//true

JDK 7/8 下,String 类型的字符串常量池在 JVM 的堆中。
在如上的代码中,s1、s2是位于栈的两个引用,他们指向堆内字符串常量池中的 “hello world”。
s1 的 “hello world” 被存储到了常量池,s2 直接去常量池中创建,创建的时候发现已经有这个对象了,此时也就是指向 s1 引用对象的一个引用。所以 s2 引用就指向和 s1 一样了。因此最后的比较 s1 == s2 是 true;

备注一:通过new关键字来生成对象是在堆区进行的,而在堆区进行对象生成的过程是不会去检测该对象是否已经存在的。因此通过 new 来创建对象,创建出的一定是不同的对象,即使字符串的内容是相同的。

String的深入介绍
美团技术对String和intern方法的解析

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值