- 包装类是对象,拥有方法和字段,对象的调用都是通过引用对象的地址;基本类型不是
- 声明方式不同:
- 基本数据类型 不需要 new 关键字
- 包装类型 需要 new 在 堆内存中进行new 来分配内存空间
- 存储位置不同:
- 基本数据类型 直接将值保存在值 栈中;
- 包装类型 是把对象放在堆中,然后通过对象的引用来调用它们
- 初始值不同:
- int 初始值=0,boolean 初始值=false
- 包装类型的初始值=null
- 包装类型是引用的传递;基本类型是值传递
- package com.api.Demo07;
-
- public class Test18 {
- public static void main(String[] args) {
- /**
- * 包装类底层设计原理
- * int 与 Integer 区别
- * - int属于基本数据类型 值传递————Integer属于int包装 对象 类 引用类型
- * - 基本数据类型存放在栈空间中——局部变量表(方法)————包装类 属于对象 存放在 堆空间
- * - Integer属于包装类 默认值 null(包装类)————int基本数据类型 默认值 0
- * 实际开发中 使用 包装类 比较多
- */
- Integer integerA = 60;
- //底层帮我们 new Integer(); 赋值给integerA对象,然后给Integer 成员属性 value赋值
- /**
- * public static Integer valueOf(int i) {
- * if (i >= IntegerCache.low && i <= IntegerCache.high)
- * return IntegerCache.cache[i + (-IntegerCache.low)];
- * return new Integer(i);
- * }
- *
- * public Integer(int value) {
- * this.value = value;
- * }
- *
- * private final int value;
- */
- int intA = 60;
- System.out.println(integerA);//60
- /**
- * integer是一个对象,为什么直接可以System.out.println(integerA);输出呢,而不是对象的内存地址呢?
- * ∵ Integer(包装类)重写了toString(),输出对应的基本数据类型
- *
- * public void println(Object x) {
- * String s = String.valueOf(x);
- * synchronized (this) {
- * print(s);
- * newLine();
- * }
- * }
- *
- * public static String valueOf(Object obj) {
- * return (obj == null) ? "null" : obj.toString();
- * }
- *
- * public String toString() {
- * return toString(value);
- * }
- */
- }
- }
- package com.api.Demo07;
-
- public class Test19 {
- private Integer integerA;
- private Boolean aBoolean;
- private int intA;
- private byte byteA;
- private short shortA;
- private long longA;
- private char charA;
- private boolean booleanA;
- private float flaotA;
- private double doubleA;
- private String stringA;
-
- public static void main(String[] args) {
- new Test19().show();
- }
- public void show(){
- System.out.println(integerA);//null
- System.out.println(aBoolean);//null
- System.out.println(intA);//0
- System.out.println(byteA);//0
- System.out.println(shortA);//0
- System.out.println(longA);//0
- System.out.println(charA);// 没有输出任何值
- System.out.println(booleanA);//false
- System.out.println(flaotA);//0.0
- System.out.println(doubleA);//0.0
- System.out.println(stringA);//null
- }
-
- }
下一篇文章:装箱和和拆箱设计原理