Java 基本数据类型的包装类

基本数据类型的包装类

基本数据类型     包装类
* byte          Byte    
* short         Short
* int           Integer
* long          Long
* float         Float
* double        Double
* boolean       Boolean
* char          Character

思考:为什么要把基本数据类型封装成一个类
在类中可以声明方法,可以使用对象调用方法

Integer

private static void Demo() {
    // 创建一个 Integer 对象
    Integer integer1 = new Integer(10);
    System.out.println(integer1);
    // 把字符串转换成 Integer 类型
    // 注意:是数字格式字符串才能转换
    Integer integer2 = new Integer("100");
    System.out.println(integer2);

    int a = 60;
    System.out.println("二进制:" + Integer.toBinaryString(a));
    System.out.println("八进制:" + Integer.toOctalString(a));
    System.out.println("十六进制:" + Integer.toHexString(a));

    // int 和 Integer 之间的转换,静态方法
    Integer num1 = Integer.valueOf(10);
    // 把 Integer 类型转换成 int 类型
    int num2 = num1.intValue();

    // String 和 Integer 之间的转换
    Integer num3 = Integer.valueOf("1000");
    String string3 = num3.toString();
    // 把字符串转换成 int
    Integer.parseInt("100");
}
注意:
Integer num1 = 100;
Integer num2 = 100;
// == 比较地址
System.out.println(num1 == num2);// true
// Integer 中的 equals 方法,比较 int 值
System.out.println(num1.equals(num2));// true

// 传入的值,如果在-128到127之间
// 从数组中去除一个对象返回
// 超出[-128,127]这个区间,返回的是新创建的对象,相当于new Integer(150)
Integer num3 = 150;
Integer num4 = 150;
System.out.println(num3 == num4);// false
System.out.println(num3.equals(num4));// true

Integer num5 = new Integer(100);
Integer num6 = new Integer(100);
System.out.println(num5 == num6);// false
System.out.println(num5.equals(num6));// true

JDK1.5 自动装箱和自动拆箱

private static void fun2() {
    // 系统会自动装箱,调用方法
    // 初值不要给 null,避免计算中发生错误
    Integer num1 = 10;// 相当于 Integer num2 = Integer.valueOf(10);
    // 系统把 num1 自动拆箱,转换回了 int 类型 
    int rel = num1 + 5;// 相当于调用了 num1.intValue

    System.out.println(num1 + rel);
}

http://blog.csdn.net/huzongnan/article/list

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值