Day 29 : Wrapper Classes

Chi-Tse Chiang
2022-10-14 23:53:51

Intro

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:

Auto boxing

Dclaration

/*Wrapper_Class variable_name = data;*/
Integer num = 12;
Character gpa = 'A';

This means that the original data type is placed inside the object by wrapping it.You can also declare the general type first and then wrap it.

int num = 12;
Integer new_wrapper = num;

valueOf

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());

This program can pay attention to two things:

1. The way primitive data types are wrapped into objects

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

2. Print the contents

This uses data type + Value () to print the contents of the basic wrapper

compareTo

Integer provides a method for comparing with other objects of the same type:

1. If the values are the same, 0 is returned

2. If the value is greater than the input value, 1 is returned

3. If the value is less than the input value, -1 is returned

Integer num = 12;
Integer wra = 24;
System.out.println(num.compareTo(wra));     //Outputs : -1

Auto unboxing

In simple terms, after packaging, unpack and save the contents in their original format.

Integer num = 12;
int temp = num;  //編譯器在此步驟拆箱