包装类

八中基本数据类型不是对象。
把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
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值