Load: http://blog.csdn.net/maggiedorami/article/details/7944459
Java provides a set of basic data types, including Boolean, Byte, char, short, int, long, float, double. Java also provides these types of encapsulation classes, Boolean, Byte, Character, short, Integer, Long, Float, Double, respectively.
Since the basic type is provided, why use the encapsulation class?
- In some cases, the data must appear as an object, and the wrapper class must be used to encapsulate the simple type as an object.
- For example, if you want to use list to hold values, because only objects are added to the list, we need to encapsulate the data in the encapsulation class and then join the list. After the JDK5.0 can be automatically sealed, can be abbreviated to the form of List.add (1), but the added data is still the encapsulated object.
- In addition, in some cases, we will also write this method, such as Func (Object o), which can accept all types of object data, but for simple data types, we must use objects that encapsulate the class.
- In some cases, the use of encapsulation classes allows us to manipulate data more conveniently. For example, the encapsulation class has some basic types of methods that are not available, such as valueof (), toString (), and a convenient way to return various types of data, such as Integer Shortvalue (), Longvalue (), Intvalue (), and so on.
There are some differences between the basic data types and their corresponding encapsulation classes because of their nature:
- The base data type can only be passed by value, while the encapsulated class is passed by reference.
- The base type is created on the stack, whereas for object types, objects are created in the heap, and references to objects are created in the stack. The base type is more efficient in the stack, but there may be a memory leak problem.
Basic data types in Java and encapsulation classes