包装类、String与基本数据类型的转换

一、包装类

JAVA提供了俩种数据类型:基本数据类型和引用数据类型
引用数据类型,其实就是各种JAVA jdk提供的类
包装类只要用在泛型< E >中

  1. 包装类
    很多时候,我们需要创建对象来解决问题,如ArrayList< E >,其中E必须是一个引用数据类型,如果想使用基本数据类型,就必须使用基本数据类型对应的引用数据类型,即包装类。
    包装类在将基本数据类型包装为引用数据类型的同时,也定义了对基本数据类型操作的方法

  2. 基本数据类型对应的包装类

    本类型包装类
    byteByte
    shortShort
    intInteger
    longLong
    floatFloat
    douleDouble
    charCharacter
    booleanBoolean
  3. 装箱与拆箱
    装箱:
    (1)使用构造方法

    包装类名(int value) 
          //构造一个新分配的 Integer 对象,它表示指定的 int 值。 
    包装类名(String s) 
          //构造一个新分配的 Integer 对象,它表示 String 参数所指示的 int 值。 
          //这里的字符串中的内容必须和包装类对应的基本数据类型一致
          //如Integer("100") 正确,Integer("fg"),Integer("1.5")错误
    

    (2)使用静态方法

    static 包装类名 valueOf(int i) 
              //返回一个表示指定的 int 值的 包装类 的 实例。 
    static 包装类名 valueOf(String s) 
              //返回保存指定的 String 的值的 包装类 的 对象。作用:把字符串转换为对应类型的数据 
    

    拆箱:使用成员方法
    格式:基本数据类型 基本数据类型value()如:

     int intValue()int 类型返回该 Integer 的值。 
      byte byteValue() 
              作为一个 byte 返回此 Byte 的值。 
    
  4. 自动装箱/自动拆箱
    在JAVA5版本之后实现的
    自动装箱:直接把基本数据类型的值赋值给包装类
    自动拆箱:包装类不能进行基本运算,但它会自动转换为基本数据类型

  5. 示例

    package linxu.day15;	
    import java.util.ArrayList;
    public class demomeian {
        public static void main(String[] args) {
            //装箱与拆箱
            Integer integer=new Integer(10);
            Integer integer1=new Integer("100");
            Integer integer2=Integer.valueOf(10);
            Integer integer3 = Integer.valueOf("10");
            int i = integer.intValue();
            //自动装箱与自动拆箱
            Integer integer4=5;//自动装箱不需要new,直接赋值即可
            integer4+=5;
            //相当于:integer4= integer4+5;-->Integer temp=integer4.intValue()+5-->integer4=new Integer(temp)
            //可以看出自动拆箱的步骤其实很多,只是省略了
    
            ArrayList<Integer> list=new ArrayList<>();
            list.add(1);//相当于自动装箱
            Integer integer5=list.get(0);//正常情况下Integer接受
            int in=list.get(0);//自动拆箱 相当于list.get(0).intValue();
        }
    }
    
    

二、String与基本数据类型的转换

  1. 基本数据类型转换为String
    (1)基本数据类型直接和字符串拼接,如:String s=56+"sbs";
    (2)使用包装类的toString静态方法

    String toString(int i); 
          //返回一个 String 对象。 所有包装类都有toString方法
    

    (3)使用String类的静态方法

    String valueOf(int i);
    
  2. String转换为基本数据类型
    使用parse方法
    使用包装类的静态方法

    static byte parseByte(String s) 
    	         // 将 string 参数解析为有符号的十进制 byte。
    	static int parseInt(String s) 
    	         // 将字符串参数作为有符号的十进制整数进行解析 
    	 //除了Character都有parse方法
    
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值