基本数据类型与其对应的封装类之间的相互转换


一、基本数据类型与其对应的封装类之间的相互转换

     1.基本数据类型转换为封装类

        有三种方法:

        a.直接赋值  (自动装箱)       

[java]  view plain  copy
  1. Integer i=3;  
        b.使用封装类的含参构造方法(实例化)

[java]  view plain  copy
  1. Integer i=new Integer(3);  

        c.使用封装类提供的valueOf()方法(静态方法)

[java]  view plain  copy
  1. Integer i=Integer.valueOf(3);  

    2.封装类转换为基本数据类型

       有两种方法:

       a.直接赋值(自动拆箱)

[java]  view plain  copy
  1. Integer i=new Integer(2);  
  2. int j=i;  
        b.使用封装类提供的value()方法

[java]  view plain  copy
  1. Integer i=new Integer(3);  
  2. int j=i.intValue();  
  3. float f=i.floatValue();  
二、基本数据类型与字符串之间的相互转换       

       1.基本数据类型转换为字符串

          有三种方法:

          a.使用String类的valueOf()方法(静态方法)

[java]  view plain  copy
  1. String s=String.valueOf(123);  
          b.使用封装类的toString()方法(静态方法)

[java]  view plain  copy
  1. String s=Integer.toString(3);  

          c.使用字符串连接符“+”

[java]  view plain  copy
  1. String s=""+123;  
       2.字符串转换为基本数据类型

          有一种方法:

          a.使用封装类的静态方法

[java]  view plain  copy
  1. int i=Integer.parseInt("12");  
三、封装类与字符串之间的相互转换

       1.字符串转换为封装类          

          有两种方法:

          a.使用封装类的含参构造方法(实例化)

[java]  view plain  copy
  1. Integer i=new Integer("123");  

          b.使用封装类的valueOf()方法

[java]  view plain  copy
  1. Integer i=Integer.valueOf("123");  

       2.封装类转换为字符串

          有三种方法:

          a.使用字符串连接符“+”

[java]  view plain  copy
  1. Integer i=new Integer(123);  
  2. String s=""+i;  

         b.使用封装类的toString()方法

[java]  view plain  copy
  1. Integer i=new Integer(123);  
  2. String s=i.toString();  


          c.使用String类的valueOf()方法

[java]  view plain  copy
  1. Integer i=Integer.valueOf(123);  
  2.   
  3. String s=String.valueOf(i);  


 
四、总结 

         以上所列都是基本数据类型、封装类和字符串两两之间的直接转换,因此,可以衍生出来一些其他的东西,类似数学中的等量代换吧

举例说明:

[java]  view plain  copy
  1. Integer i=new Integer(23);  
  2. String s=Integer.toString(i);  

这两行代码中,封装类Integer的toString方法要求的参数是基本数据类型int,但是变量i是int的封装类,所以这里就有一个把Integer转换为int的过程,即自动装箱


http://blog.csdn.net/feiyudiaoling/article/details/51354413

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值