基本类型的包装类
1.1 基本类型的包装类概述
将基本数据类型封装成对象的好处在于可以在对象中定义更多的功能方法操作该数据;
基本数据类型 | 包装类 |
---|---|
byte | Byte |
short | Short |
int | Integer |
long | Long |
float | Float |
double | Double |
char | Character |
boolean | Boolean |
1.2 Integer 类的概述和使用
Integer:包装一个对象中的原始类型int的值
方法名 | 说明 |
---|---|
public Integer(int value) | 根据 int 值创建 Integer 对象 |
public Integer(String s)(数字组成的字符串) | 根据 String 的值创建 Integer 对象 |
public static Integer valueOf(int i) | 返回表示指定的 int 值的 Integer 实例 |
public static Integer valueOf(String s) | 返回一个保存指定值的 Integer 对象 String |
1.3 int 和String的相互转化
- int 转换为 String
public static String valueOf(int i):返回 int 参数的字符串表示形式。该方法是String类中的方法
- String 转换为 int
public static int parseInt(String s):将字符串解析为int类型,该方法是Integer 类中的方法
public class IntegerDemo {
public static void main(String[] args) {
//int --- String
int number = 100;
//方式1
String s1 = "" + number;
System.out.println(s1);
//方式2------public static String valueOf(int i)
String s2= String.valueOf(number);
System.out.println(s2);
System.out.println("================");
//String ---- int
String s = "100";
// 方式一
//String---Integer---int
Integer i = Integer.valueOf(s);
//public int intValue()
int x = i.intValue();
System.out.println(x);
//方式二:String----int
//public static int parseInt(String s)
int y = Integer.parseInt(s);
System.out.println(y);
}
}
public String[] split(String regex)
将此字符串拆分为给定的regular expression的匹配。
该方法的工作原理是通过使用给定表达式和限制参数为零调用双参数split方法。因此,尾随的空字符串不会包含在结果数组中。
例如,字符串"boo:and:foo"使用以下表达式得到以下结果:
Regex Result
: { "boo", "and", "foo" }
o { "b", "", ":and:f" }
1.4 自动装箱和拆箱
- 装箱:把基本数据类型转换为对应的包装类型
- 拆箱:把包装类类型转换为对应的基本数据类型
Integer i= 100;//自动装箱
i+=200; //i=i+200; i+200(自动拆箱);i=i+200;(自动装箱)
注意:在使用包装类类型的时候,如果做操作,最好先判断是否为null