The day before the countdown, today we will introduce the concept of wrapping primitive data types into objects – Wrapper Classes
which actually wraps the Primitive Data Types we mentioned earlier and allows them to operate as objects.
(If you are not familiar with it, you can refer to Day 6: Variables (2)))
The wrapped object will contain a variable and its data type
The following is the conversion of the original data type to the corresponding Wrapper Class:
/*Wrapper_Class variable_name = data;*/
Integer num = 12;
Character gpa = 'A';
int num = 12;
Integer new_wrapper = num;
This is not quite the same as declaring variables in general.
When creating an object, new
is used to create a new object, and the wrapper method wraps the variable into an object format via valueOf
.
int num = 12;
double num2 = 12.33;
var wra1 = Integer.valueOf(num);
var wra2 = Doublie.valueOf(data1);
System.out.println(wra1.intValue());
System.out.println(wra2.doubleValue());
The initial declaration of the variable, and the two middle paragraphs (var represents the declaration of an untyped variable) are how the compiler turns it into an object
The compiler uses Wrapper Class + valueOf to create an instance of the wrapper
This uses “data type + Value ()” to print the contents of the basic wrapper
Integer provides a method for comparing with other objects of the same type:
Integer num = 12;
Integer wra = 24;
System.out.println(num.compareTo(wra)); //Outputs : -1
In simple terms, after packaging, unpack and save the contents in their original format.
Integer num = 12;
int temp = num; //編譯器在此步驟拆箱