包装类

来源:互联网 发布:4k网络机顶盒排名前十 编辑:程序博客网 时间:2024/06/11 16:22

八中基本数据类型不是对象。
把int等基本数据类型包装成一个类,就可以以对象的形式操作基本数据类型。
下面以Integer和Float为例:
装箱及拆箱:
A 将基本数据类型变为包装类,称为装箱
B 将包装类的类型变为基本数据类型,称为拆箱

public class WrapperDemo01{    public static void main(String[] args)    {        int x = 20 ;    //基本数据类型        Integer i = new Integer(x) ; //装箱,将基本数据类型变为包装类        int temp = i.intValue() ;    //拆箱, 将包装类变为基本数据类型    }}

以float类型为例

public class WrapperDemo02{    public static void main(String[] args)    {        float x = 20.3f ;   //基本数据类型        Float f = new Float(x) ; //装箱,将基本数据类型变为包装类        float y = f.floatValue() ;   //拆箱, 将包装类变为基本数据类型    }}

自动装箱 和 自动拆箱 操作

public class WrapperDemo03{    public static void main(String[] args)    {        Integer i = 30 ;        //自动装箱操作         Float f = 18.2f ;       //自动装箱操作        int x = i ;             //自动拆箱操作        int y = f ;             //自动拆箱操作    }}

在包装类中,存在最大特点 ,就是可以将字符串变成指定的数据类型

public class WrapperDemo04{    public static void main(String[] args)    {        String str1 = "20" ;    //由数字组成的字符串        String str2 = "12.2" ;  //由数字组成的字符串        int i = Integer.parseInt(str1) ; //将字符串变为int型        float f = Float.parseFloat(str2) ; //将字符串变为float型        System.out.println("整数乘方:"+i+"*"+i+"="+(i*i)) ;        System.out.println("小数乘方:"+f+"*"+f+"="+(f*f)) ;    }}
public class WrapperDemo05{    public static void main(String[] args)    {        int i = Integer.parseInt(args[0]) ; //从初始化参数上输入信息        float f = Float.parseFloat(args[1]) ; //从初始化参数上输入信息        System.out.println("整数乘方:"+i+"*"+i+"="+(i*i)) ;        System.out.println("小数乘方:"+f+"*"+f+"="+(f*f)) ;    }}
0 0