目录
- Java中的基本数据类型及包装类对应
- 分类及特性
- 包装类中==与equals的用法比较
- 包装类应用:String int 转换
说到Java中的包装类就不得不介绍一下Java中的基本数据类型(8种):byte、short、int、long、float、double、char、boolean。下面以表格的形式详细介绍这八种数据类型:
Java中的基本数据类型及包装类对应
byte | short | int | long | float | double | char | boolean | |
位数 | 8 | 16 | 32 | 64 | 32 | 64 | 16 | 1 |
字节数 | 1 | 2 | 4 | 8 | 4 | 8 | 2 | 1 (1/8) |
默认值 | 0 | 0 | 0 | 0L | 0.0f | 0.0d | false | |
包装类型 | Byte | Short | Integer | Long | Float | Double | Character | Boolean |
特别说明:
- char类型占2个字节,可以表示汉字,所以无论是汉字还是英文字符都占2字节
- boolean类型理论上占1bit(1/8字节),而实际中按1byte(1字节)处理
分类及特性
常用的包装类可以分为三类:Character、Number、Boolean,具体见上表所示。
这里总结一下包装类的一些特性:
- 所有包装类都可以将与之对应的基本数据类型作为参数来创建它们的实例对象
- 自动装箱和拆箱
- 自动装箱:把基本类型转换为包装类类型
int m = 10;
Integer in = m; //Integer in = Integer.valueOf(m);
System.out.println(in);//10
- 自动拆箱:把包装类类型转换为基本类型
Integer inn = Integer.valueOf(10);//不推荐用new Integer(String)方法
int n = inn; //int n = inn.intValue();
System.out.println(n);//10
- 除了Character类之外,其他包装类都可以将一个字符串作为参数来构造它们的实例
- Boolean类的构造方法参数为String类型时,若该字符串为true(不论大小写),则该对象表示true,否则表示false
- 当包装类Number构造方法的参数为String类型时,字符串不能为null(建议先判断是否为null,然后再使用),并且该字符串必须能够解析为基本类型的数据
/*
* 当包装类Number构造方法的参数为String类型时,字符串不能为null
* 并且该字符串必须能够解析为基本类型的数据
* 否则会抛出数字格式异常。
*/
Integer a2 = new Integer("");//NumberFormatException: For input string: ""
Integer a3 = new Integer(null);//NumberFormatException: null
Integer a4 = new Integer("abc");//NumberFormatException: For input string: "abc"
包装类中==与equals的用法比较
equals:比较对象的内容
==:比较变量的值,对于两个包装类对象则是比较首地址,一个包装类对象一个基本数据,包装类自动拆箱
Integer x = 1;
System.out.println(x == 1); // true 自动拆箱
Integer y = 1000;
System.out.println(y == 1000); // true 自动拆箱
包装类如Integer,具有一个内部静态类IntegerCache,用来缓存[-128,127]之间的Integer对象;
在此范围内自动装箱或者调用Integer.valueOf()方法,能够从缓存中引用相应的对象;
超过此范围会新生成对象,由此可发现以下情况:
Integer i1 = Integer.valueOf(100);
Integer i2 = Integer.valueOf(100);
Integer i3 = Integer.valueOf(130);
Integer i4 = Integer.valueOf(130);
System.out.println(i1==i2);//true,引用同一对象
System.out.println(i3==i4);//false,两者非同一对象
包装类应用:String int 转换
String s = "123";
Integer x = new Integer(s);
int i = x.intValue();
int i1 = Integer.parseInt(s);