有关包装类的概念、装箱和拆箱、基本数据类型和字符串的相互转换

一:包装类的概念

概述:
基本数据类型使用方便,但是没有对应的方法来使用这些数据,因此我们可以使用一个类,把基本数据类型包装起来,这个类就叫做“包装类”。在包装类中可以定义一些基本的方法,来操作基本类型的数据。

包装类对应的八种基本数据类型

基本数据类型对应的包装类(java.lang包)
byteByte
shortShort
intInteger
longLong
floatFloat
doubleDouble
charCharacter
booleanBoolean

二:装箱与拆箱

装箱:从基本类型转换为包装类对象

 public static void main(String[] args) {
        int a = 10;
        Integer b = a; //自动装箱
}

 拆箱:从包装类对象转换为对应的基本类型

public static void main(String[] args) {
        Integer c = 11;
        int d = c;  //自动拆箱
    }

 代码示例:

        //基本数据类型和包装类型
        int a1=5;
        Integer a2=new Integer(5);
        System.out.println(a1);
        System.out.println(a2);
 
        //装箱
        Integer a3=new Integer(a1);
        Integer a4=Integer.valueOf(a1);
        //拆箱
        int a5=a3.intValue();
 
        //自动装箱与自动拆箱
        //自动装箱
        Integer a6=a1;
        //自动拆箱
        int a7=a3;

三:基本类型与字符串类型之间的相互转换

包装类可以把基本类型的数据转换为字符串形式

基本类型->字符串(String)

代码示例:

    public static void main(String[] args) {
        Integer a=10;
        String b=a.toString();
        System.out.println(b+1);

        String c=Integer.toString(a);
        System.out.println(c+1);

        String d=a+"";
        System.out.println(d+1);
    }

 运行结果:

 

 

 字符串(String)->基本类型

         //字符串(String)->基本类型
        int n = Integer.parseInt("123");
        double h = Double.parseDouble("3.14");
        System.out.println(n);
        System.out.println(h);
        System.out.println("-------");
        int n1 = Integer.parseInt("8D3FE", 16);
        System.out.println(n1);

 运行结果:

 

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值