什么是包装类?
包装类把基本类型数据转换为对象
每个基本类型在java.lang包中都有一个相应的包装类
基本数据类型 | 对应的包装类 |
---|---|
byte | Byte |
short | Short |
int | Integer |
long | Long |
char | Character |
float | Float |
double | Double |
boolean | Boolean |
包装类有何作用:
提供了一系列实用的方法集合不允许存放基本数据类型数据,存放数字时,要用包装类型
所有包装类都可将与之对应的基本数据类型作为参数,来构造它们的实例
如:Integer i=new Integer(1);
如: Integer i=new Integer("123");
基本类型和对应的包装类可以相互装换:
Integer inter=new Integer(20);
int in=inter.intValue();
Value of():基本数据类型转换成包装类
Integer intValue=Integer.valueOf(12);
toString():以字符串形式返回包装对象表示的基本类型数据
String sex=Character.toString(‘男‘);
String id=Integer.toString(25);
或者
String sex=‘男‘+"";
String id=25+"";
parseXXX():把字符串转换为相应的基本数据类型数据(Character除外)
int num=Integer.parseInt("36");boolean bool=Boolean.parseBoolean("false");
所有包装类都是final类型,不能创建它们的子类JDK1.5后,允许基本数据类型和包装类型进行混合数学运算包装类并不是用来取代基本数据类型的在基本数据类型需要用对象表示时使用
注意:
1.Boolean类构造方法参数为String类型时,若该字符串内容为true(不考虑大小写),则该Boolean对象表示true,否则表示false
2.当包装类构造方法参数为String 类型时,字符串不能为null,且该字符串必须可解析为相应的基本数据类型的数据,否则编译通过,运行时NumberFormatException异常
public static void main(String[] args) { 2 //所有包装类都可以将与之对应的基本数据类型作为参数来创建它们的实例对象 3 Integer a = new Integer(100); 4 Double b = new Double(100.00); 5 Character c = new Character(‘A‘); 6 Boolean d = new Boolean(true); 7 System.out.println(a+" "+ b+" "+c+" "+d);//100 100.0 A true 8 9 //除了Character类之外,其他包装类都可以将一个字符串作为参数来构造它们的实例 10 Integer a1 = new Integer("100"); 11 Double b1 = new Double("100.00"); 12 Boolean d1 = new Boolean("true"); 13 System.out.println(a1+" "+ b1+" "+d1);//100 100.0 true 14 15 /* 16 * Boolean类的构造方法参数为String类型时: 17 * 若该字符串为true(不论大小写),则该对象表示true,否则表示false 18 */ 19 Boolean d2 = new Boolean("True"); 20 Boolean d3 = new Boolean("TRUE"); 21 Boolean d4 = new Boolean("hello"); 22 System.out.println(d2+" "+d3+" "+d4);//true true false 23 24 /* 25 * 当包装类Number构造方法的参数为String类型时,字符串不能为null 26 * 并且该字符串必须能够解析为基本类型的数据 27 * 否则会抛出数字格式异常。 28 */ 29 Integer a2 = new Integer("");//NumberFormatException: For input string: "" 30 Integer a3 = new Integer(null);//NumberFormatException: null 31 Integer a4 = new Integer("abc");//NumberFormatException: For input string: "abc" 32
原文:https://www.cnblogs.com/bokedizhi97/p/13060984.html