There are basic types in Java why is there a wrapper type? 1. Basic data types and package types in Java are:
Basic Type |
Wrapper Type |
Parent Class |
Boolean |
Boolean |
Java.lang.Boolean |
Int |
Integer |
Java.lang.Number |
Char |
Character |
Java.lang.Character |
Byte |
Byte |
Java.lang.Number |
Short |
Short |
Java.lang.Number |
Long |
Long |
Java.lang.Number |
Double |
Double |
Java.lang.Number |
Float |
Float |
Java.lang.Number |
2. Why are there two types of these?
We all know that in the Java language, the new object is stored in the heap, and we use those objects through references in the stack, but for a series of types such as int that are often used, it is not very effective if we store them in the heap with new-especially simple small variables. So there's the basic type, like C + +, where Java uses a similar approach, which is more efficient when it's not created with the new keyword, but instead directly stores the value of the variable in the stack.
3. Why do we have to have a package type with a basic type?
We know that Java is a programming language of a Face object, the basic type does not have the nature of the object, in order to let the basic type also has the characteristics of the object, there is a wrapper type (if we use the collection type collection must use the wrapper type rather than the base type), it is equivalent to the basic type " Wrapping ", so that it has the nature of the object, and adds properties and methods to it, enriching the operation of the basic type.
In addition, when you need to put things into the arraylist,hashmap, like int,double this basic type is not put in, because the container is loaded with object, which is the need for these basic types of wrapper class.
4, the two convert each other:
1) int to Integer
int i = 0; Integer ii = new Integer(i);
2) Integer to int
Integer ii = new Integer(0);
5, the difference between the two:
1) declaration in different ways:
The base type does not use the New keyword, and the wrapper type needs to allocate storage space in the heap using the new keyword;
2) different storage methods and locations:
The base type is to store the value of the variable directly in the stack, and the wrapper type is to put the object in the heap and then use it by reference;
3) Different initial values:
The initial value of the base type, such as int is 0,boolean to false, and the initial value of the wrapper type is null;
4) Different ways of use:
The basic type is directly assigned directly to the value, and the wrapper type is used in collections such as collection, map, and so on.
Why do you have a wrapper type when you have a basic type in Java?