学习时间
2020-12-17
学习内容
基本类型包装类
基本类型和包装类的对应
byte Byte
short Short
int Integer
long Long
float Float
double Double
char Character
boolean Boolean
Integer类
概述
Integer 类在对象中包装了一个基本类型 int 的值。Integer 类型的对象包含一个 int 类型的字段。
此外,该类提供了多个方法,能在int类型和 String类型之间互相转换,还提供了处理 int 类型时非常有用的其他一些常量和方法。
构造方法
public Integer(int value)
public Integer(String s) //要个一个字面上是数字的字符串,否则就会报错
演示:
public class Test2 {
public static void main(String[] args) {
Integer i1 = new Integer(12);
Integer i2 = new Integer("10086");
Integer i3 = new Integer("12a");
System.out.println(i1);//12
System.out.println(i2);//10086
System.out.println(i3);//NumberFormatException
}
}
练习
看程序写结果
public class Test2 {
public static void main(String[] args) {
Integer i1 = new Integer(127);
Integer i2 = new Integer(127);
System.out.println(i1 == i2);//true
System.out.println(i1.equals(i2));//true
System.out.println("-----------");
Integer i3 = new Integer(128);
Integer i4 = new Integer(128);
System.out.println(i3 == i4);//false
System.out.println(i3.equals(i4));//true
System.out.println("-----------");
Integer i5 = 128;
Integer i6 = 128;
System.out.println(i5 == i6);//false
System.out.println(i5.equals(i6));//true
System.out.println("-----------");
Integer i7 = 127;
Integer i8 = 127;
System.out.println(i7 == i8);//true
System.out.println(i7.equals(i8));//true
}
}
String和int类型的相互转换
int -- String
a:和""进行拼接
b:public static String valueOf(int i)
c:int -- Integer -- String
String -- int
a:String -- Integer -- intValue();
b:public static int parseInt(String s)
演示:
1、
import static java.lang.String.valueOf;
public class Test2 {
public static void main(String[] args) {
int a = 10;
int b = 20;
int c = 30;
String s1 = a + "";
String s2 = valueOf(b);
Integer i3 = new Integer(c);
String s3 = i3.toString();
}
}
2、
public class Test2 {
public static void main(String[] args) {
String s1 = "123";
String s2 = "345";
Integer integer1 = new Integer(s1);
int i1 = integer1;
System.out.println(i1);
Integer integer2 = new Integer(s2);
int i2 = Integer.parseInt(s2);
System.out.println(i2);
}
}
自动装箱和拆箱
JDK5的新特性:
自动装箱:把基本类型转换为包装类类型
自动拆箱:把包装类类型转换为基本类型
注意事项:
在使用时,Integer x = null;代码就会出现NullPointerException。
建议先判断是否为null,然后再使用。
演示:
1、
public class Test2 {
public static void main(String[] args) {
Integer a = 100;
a += 20;
System.out.println(a);//120
}
}
2、
public class Test2 {
public static void main(String[] args) {
Integer a = null;
a += 20;
System.out.println(a);//NullPointerException
}
}