Java包装类介绍与类型之间相互转换

Java包装类介绍与类型之间相互转换

1、包装类存在的意义

通俗解释就是由于Java是面对对象的语言,而基本类型不具有面对对象的概念,为了弥补不足,引入了包装类方便使用面对对象的变成思想操作基本类型。

2、基本类型和包装类对应关系

byte

Byte

int

Integer

short

Short

long

Long

float

Float

double

Double

boolean

Boolean

char

Character

注:String不是基本类型,所以不存在包装类的概念。很多初学者容易混淆这个概念。

3、包装类的使用

以Integer类为例,其它类可以翻阅API文档查阅:

 1     public static void main(String[] args) {
 2         Integer i = new Integer(5);// 通过构造函数把int类型转换为Integer类型。
 3         Integer j = new Integer("5");// 通过构造函数把String类型的数值转为int类型后再转为Integer类型,如果String中不包含数值,则会出现异常。
 4         int temp = 10;
 5         Integer m = temp;// 自动装箱
 6         Integer n = new Integer(temp);// 自动装箱
 7         int x = m.intValue();// 手动拆箱
 8         int y = n;// 自动拆箱
 9         System.out.println(i + "\t" + j + "\t" + m + "\t" + n + "\t" + x + "\t" + y);
10     }

运行结果:

5    5    10    10    10    10

4、基本类型与包装类转换为String

a、使用toString转换

1     public static void main(String[] args) {
2         int i = 50;
3         String str = Integer.toString(i);//自动装箱并调用toString()方法,这也是将基本类型转换为包装类的好处。
4         System.out.println(str);
5     }

运行结果:

50

b、使用valueOf转换

1     public static void main(String[] args) {
2         String str = String.valueOf("10");
3         System.out.println(str);
4     }

运行结果:

10

c、数字+""方法

1     public static void main(String[] args) {
2         int i = 100;
3         String str = i + "";
4         System.out.println(str);
5     }

运行结果:

100

 5、包装类转换为基本类型

1     public static void main(String[] args) {
2         Integer i = new Integer("20");
3         int m = i.intValue();
4         System.out.println(m);
5     }

运行结果:

20

6、字符串转换为基本类型

1     public static void main(String[] args) {
2         int i = Integer.parseInt("50");
3         System.out.println(i);
4     }

运行结果:

50

猜你喜欢

转载自www.cnblogs.com/min-li/p/9720716.html
今日推荐