包装类与基本数据类型与String类型之间的相互转换

包装类与基本数据类型与String类型之间的相互转换

  • 包装类与基本数据类型
    • 基本数据类型---->包装类
      • 通过构造器

        Integer  t = new Integer(11);
        
      • 通过自动装箱

        Integer t1 = 11;
        
      • 通过 包装类的valueOf( 基本数据类型) 来转换

        Integer  i=Integer.valueOf(123);  // 有缓存区
        
    • 包装类—>基本数据类型
      • 调用包装类的方法

        Integer i = new Integer(11);
        int num3= i.intValue();//调用包装类的方法
        
        //源码:  Integer类中
        public int intValue() {
            return value;
        }
        
      • 自动拆箱

        int num2 =i;//自动拆箱
        
  • 包装类与字符串类型
    • 字符串类型—>包装类
      • 通过字符串参数

        Integer i3=new Integer("456");
        //调用字符串参数
        
      • 使用包装类的 parseXxx(String str)静态方法 (间接的转换)

        Integer i4=Integer.parseInt("1234556");
         //该方法返回的是int型,后通过自动装箱成包装类
        
        //源码:  Integer类中
        public static int parseInt(String s) throws NumberFormatException {
            return parseInt(s,10);
        }
        
    • 包装类—>字符串类型
      • 调用包装类 对象的toString(); 方法

        String str2= i.toString();//(i是包装类对象)
        //调用包装类对象的toString方法
        
        //底层代码 : Integer类中
        public String toString() {
            return toString(value);
        }
        
      • 调用包装 类的toString(形参); 方法

        String str3=Integer.toString(i);
        //调用包装类的toString(形参)方法
        
        //底层代码:  Integer类中
        public static String toString(int i){
            int size = stringSize(i);
            if (COMPACT_STRINGS) {
                byte[] buf = new byte[size];
                getChars(i, size, buf);
                return new String(buf, LATIN1);
            } else {
                byte[] buf = new byte[size * 2];
                StringUTF16.getChars(i, size, buf);
                return new String(buf, UTF16);
            }
        }
        
  • 字符串类型与基本数据类中
    • 基本数据类型—>字符串
      • 通过与空字符串连接

        String str= 20+"";
        
      • 通过String类中的valueOf() 方法将基本数据类型转换到字符串类型

        String  str=valueOf(123);
        //  通过String类中的valueOf() 方法将基本数据类型转换到字符串类型
        //源码:  String类中
          public static String valueOf(int i) {
          return Integer.toString(i);
          }
        
    • 字符串转—>基本数据类型
      • 调用包装 类的parsseXxx()方法

        int num4=Integer.parseInt("12345");
        //调用包装类的parseXxx(String str)方法
        
        //源码: Integer类中
        public static int parseInt(String s) throws NumberFormatException {
            return parseInt(s,10);
        }
        
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值