Day14_类型转换与装箱、拆箱

包装类

什么是包装类?

  • 基本数据类型所对应的引用类型。

类型转换与装箱、拆箱

  • 8种包装类提供不同类型间的转换方式:

    • Number父类中提供的6个共性方法。
    • parseXXX()静态方法。
    • valueOf()静态方法。
  • 注意:需保证类型兼容,否则抛出NumberFormatException异常。

    例如:String类型只能将“150”转换成int类型,不能包含字符,否则就会出现NumberFormatException异常

package com.oop.Demo11;

public class Demo01 {
    public static void main(String[] args) {
        int num = 10;
        //类型转换:装箱,基本类型转换成引用类型的过程
        //基本类型
        int num1=18;
        //使用Integer类创建对象
        Integer integer1= new Integer (num1);
        Integer integer2= Integer.valueOf (num1);

        //类型转换:拆箱,引用类型转换成基本类型
        Integer integer3=new Integer (100);
        int num2=integer3.intValue ();
        //JDK1.5之后,提供自动装箱和拆箱
        int age=30;
        //自动装箱
        Integer integer4= age;
        System.out.println ("自动装箱");
        System.out.println (integer4);
        //自动拆箱
        int age2=integer4;
        System.out.println ("自动拆箱");
        System.out.println (age2);
        System.out.println ("---------------");
        //基本类型和字符串之间的转换
        //1基本类型转换成字符串
        int n1= 255;
        //1.1使用+号
        String s1=n1+"ff";
        //1.2使用Integer中的toString()方法
        String s2=Integer.toString (n1,16);
        System.out.println (s1);
        System.out.println (s2);

        System.out.println("-----------boolean字符串形式转换成基本类型---------------");
        //boolean字符串形式转换成基本类型,"true"--->true   非"true"------>false
        String str2= "true";
        String str3= "hhhhh";
        boolean b1= Boolean.parseBoolean (str2);
        boolean b2= Boolean.parseBoolean (str3);
        System.out.println (b1);
        System.out.println (b2);
    }
}
原文地址:https://www.cnblogs.com/lemonlover/p/14059462.html