Java basic types of packing and unpacking
Step 1: package type
All basic types , has a corresponding class types
such as int Integer class is corresponding to
this class is called package type
package digit;
public class TestNumber {
public static void main(String[] args) {
int i = 5;
//把一个基本类型的变量,转换为Integer对象
Integer it = new Integer(i);
//把一个Integer对象,转换为一个基本类型的int
int i2 = it.intValue();
}
}
Step 2: Number The class
Digital Wrapper class has
Byte, Short, Integer, Long, Float, Double
subclasses of these classes are abstract classes Number of
package digit;
public class TestNumber {
public static void main(String[] args) {
int i = 5;
Integer it = new Integer(i);
//Integer是Number的子类,所以打印true
System.out.println(it instanceof Number);
}
}
Step 3: basic type conversion package type
package digit;
public class TestNumber {
public static void main(String[] args) {
int i = 5;
//基本类型转换成封装类型
Integer it = new Integer(i);
}
}
Step 4: Packaging basic types of transposable
package digit;
public class TestNumber {
public static void main(String[] args) {
int i = 5;
//基本类型转换成封装类型
Integer it = new Integer(i);
//封装类型转换成基本类型
int i2 = it.intValue();
}
}
Step 5: autoboxing
No need to call the constructor, automatically via the = sign converting the base type class type called boxing
package digit;
public class TestNumber {
public static void main(String[] args) {
int i = 5;
//基本类型转换成封装类型
Integer it = new Integer(i);
//自动转换就叫装箱
Integer it2 = i;
}
}
Step 6: automatic unpacking
Integer intValue no need to call the method, it is automatically converted by = int type, called unpacking
package digit;
public class TestNumber {
public static void main(String[] args) {
int i = 5;
Integer it = new Integer(i);
//封装类型转换成基本类型
int i2 = it.intValue();
//自动转换就叫拆箱
int i3 = it;
}
}
Step. 7: int maximum, minimum
Int maximum value may be obtained by Integer.MAX_VALUE corresponding package type
package digit;
public class TestNumber {
public static void main(String[] args) {
//int的最大值
System.out.println(Integer.MAX_VALUE);
//int的最小值
System.out.println(Integer.MIN_VALUE);
}
}
Exercise : boxing and unboxing
For byte, short, float, double automatic and automatic packing unpacking
It can automatically unpacking and packing between automatic and byte Integer
Byte by byte to obtain the maximum value
The answer :
package digit;
public class TestNumber {
public static void main(String[] args) {
// 1. 对byte,short,float,double进行自动拆箱和自动装箱
byte b = 1;
short s = 2;
float f = 3.14f;
double d = 6.18;
// 自动装箱
Byte b1 = b;
Short s1 = s;
Float f1 = f;
Double d1 = d;
// 自动拆箱
b = b1;
s = s1;
f = f1;
d = d1;
// 2. byte和Integer之间能否进行自动拆箱和自动装箱
Integer i1 = b; //不能把byte直接自动装箱成Integer
b = new Integer(1); //也不能把Integer自动拆箱成 byte
// 3. 通过Byte获取byte的最大值
System.out.println(Byte.MAX_VALUE);
}
}