基本类型包装类:将基本的数据类型封装成对象,其好处在于可以在对象中定义更多的功能用于操作该数据,常用于基本数据类型于字符串中的转换
基本数据类型 | 包装类 |
byte | Byte |
short | Short |
int | Integer |
long | Long |
float | Float |
double | Double |
char | Character |
boolean | Boolean |
Integer类:包装一个对象中的原始类型int的值(public final class Integer 不能再被继承)
package API;
import java.lang.Integer;
public class Iinteger {
private static final String abcdefg = null;
public static void main(String[] args) {
/*Integer构造方法
public Integer(int value) 构造一个新分配的 Integer 对象,它表示指定的 int 值。
public Integer(String s) 构造一个新分配的 Integer 对象,它表示 String 参数所指示的 int 值。
*/
Integer a=new Integer(123);
System.out.println(a);
//The constructor Integer(int) has been deprecated since version 9 and marked for removal
//构造函数整型(int)自版本9以来已被弃用,并标记为删除
Integer b=new Integer("456");
System.out.println(b);
//Integer ii=new Integer("abc");报错 只能输入整型数字
//Exception in thread "main" java.lang.NumberFormatException: For input string: "abc"
//常用方法
//public static void Integer valueOf(int i)
System.out.println(Integer.valueOf(a));//123
//public static void Integer valueOf(String s)
System.out.println(Integer.valueOf(b));//456
//int与String的相互转换
//[转换]int->String 方式一 String
int number=100;
String s1=""+number;
System.out.println(s1);//number100
//[转换]int->String 方式二 valueOf()
String s2=String.valueOf(number);
System.out.println(s2);
//[转换]String->int 方式一 String-Integer-int
Integer i=Integer.valueOf(number);
int x=i.intValue();//public static int intValue()
System.out.println(x);
//[转换]String->int 方式二 public static int parseInt(String s)
int y=Integer.parseInt(s2);
System.out.println(y);
}
}
自动装箱和拆箱
装箱:把基本数据类型转换为对应的包装类类型
拆箱:把包装类类型转换为对应的基本数据类型
Integer i=Inter.valueOf;//装箱
Integer ii=100;//自动装箱,实际也进行了上面的操作
ii=ii.intValue()+1000;//拆箱
ii+=1000;//自动拆箱(ii+1000)与自动装箱(ii=ii+1000)