java之基本数据类型的包装类

1.在程序界面存入的 数据为字符串类型,而对数据进行处理时,需要将其转换为基本数据类型,java将基本数据类型封装为包装类,方便使用

2.字符串与基本数据类型、

2.1字符串转基本数据类型:通过包装类,调用parse***()方法。

1         // 将字符串转换为int等基本数据类型 (最好不包含中文)否则编译成功但运行失败(数字转换异常)
2         int i = Integer.parseInt(s);
3         double d = Double.parseDouble(s);

2.2基本数据类型转字符串

第一种:“+“+基本数据类型,字符串的拼接

第二种:String类调用valueof(),传入基本数据类型

1 // 2.string类里的valueof(基本数据类型)8种基本数据类型
2         System.out.println(String.valueOf(123.02) + 2);

第三种:包装类调用tostring(),参数为基本数据类型

1     // 3.八个包装类的方法的重写tostring(),转换字符串
2         // 如果int类型转short类型,强转
3         System.out.println(Short.toString((short) 128));

3.基本数据类型与包装类

基本数据类型转包装类:

①通过包装类创建对象,传入参数为基本数据类型或字符串

②通过包装类直接调用valueof(),参数为基本数据类型或字符串

1 //基本数据类型转包装对象int类
2     Integer i=new Integer(123);
3     Integer i1=Integer.valueOf(123);
4     //字符串数值类型转包装类
5     Integer s=new Integer("1234");
6     Integer s1=Integer.valueOf("1234");
7     System.out.println(s1 instanceof Integer);//true

包装类转基本数据类型:

包装类对象调用intvalue()

1     Integer s=new Integer("111");
//int包装类转为基本数据类型 2 System.out.println(s.intValue());

自动装拆箱

1     //自动拆装箱
2     //基本数据类型到包装类   通过创建对象或valueof   包装类多存储null,避免空指针问题
3     Integer i=1;//引用数据类型存储的地址  
4     System.out.println(i);//重写tostring()方法
5     //包装类到基本数据类型   .intValue()
6     int a=i+2;//
原文地址:https://www.cnblogs.com/mlf19920916/p/12103477.html