Wrapper class in Java

What is a wrapper class?

The so-called wrapper class is the ability to directly represent a variable of a simple type as a class. When performing the mutual conversion of variable types, we will use these wrapper classes a lot.


Packaging class

Integer, Long, Short, Byte, Character, Double, Float, Boolean, BigInteger, BigDecmail
Among them, BigInteger and BigDecimal have no corresponding basic types, and are mainly used for high-precision operations. The remaining eight have corresponding basic types.
BigInteger supports arbitrary-precision integers, and
BigDecimal supports arbitrary-precision operations with decimal points.


Wrapper classes are used for the following purposes:

1. Collections are not allowed to store basic data types, so packaging classes are commonly used.
2. Contains the relevant attributes of each basic data type, such as maximum value, minimum value, and occupied bits.
3. As the class type corresponding to the basic data type, Provides a series of practical object operations, such as type conversion, base conversion, etc.


The difference between primitive types and wrapper types:

1. In Java, everything is an object, but the eight basic types are not objects.
2. The declaration method is different. The basic type does not need to be created by the new keyword, while the encapsulated type needs the new keyword.
3. The storage method and location are different. The basic type directly stores the value of the variable and saves it in the stack for efficient access. The encapsulated type needs to point to the instance by reference, and the specific instance is stored in the heap.
4. Depending on the initial value, the initial value of the encapsulated type is null, and the initial value of the basic type depends on the specific type. For example, the initial value of the int type is 0, and the boolean type is false;
5. Different usage methods, such as Only wrapper types can be used when working with collection classes.
6. When to use a wrapper class and when to use a basic type, it depends on the basic business: if this field allows null values, you need to use the wrapper type. If null values ​​are not allowed, you can use the basic type. To call functions such as generics and reflection, you need to use wrapper classes!

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324789030&siteId=291194637