Java basic types and wrapper types

Interview questions:

What is the difference between package type and base type? Why do we need base types when there are already wrapper types?

first question:

  1. The basic type can be created and assigned directly by defining the variable name, and the package type needs to be created and initialized through the new keyword
  2. The assignment between basic types is the transfer of inter-stack address references, which means that the same value means the same address, and the two equals are true. But the packaging types are somewhat different. The difference is that some packaging types (Integer/Char/Long/Short/Byte) have a cache mechanism, some (Double/Float) always create new objects through new, and some (Boolean) always call the same static variable . From the above, it can be known that equals is true in the scope of the cache or when static variables are called. Others have the same value but different addresses, and equals is false.
  3. There are automatic unboxing and boxing operations when basic types and packaging types are mixed
  4. The initial value of the wrapper type is null, while the basic type has a fixed initial value, for example: int is 0
  5. Wrapper types have some methods for manipulating related types, which can provide convenience for developers. But the basic type does not. This is also a manifestation of Java's object-oriented design. Only objects have specific actions (methods)
  6. Basic types are stored in stack memory, and wrapper types are stored in heap memory. The operation of stack memory is faster than that of heap memory, which is also an explanation for the next question
  7. All that can be used in the collection class are packaging types

The second question (personal opinion):

  1. The design concept of Java is that everything can be an object, so setting your own packaging type for the basic type is an operation to perfect the Java design concept from a design perspective
  2. I personally think that when using the basic type and packaging type, it needs to be considered on a case-by-case basis. For example: I use more basic data types when writing class static variables. Because more processing of magic values ​​in the code is required in the process of use, more efficiency in addressing is needed. Putting the basic type in the stack memory improves the efficiency of finding the memory address of the variable in use compared with the packaging type. However, wrapper types are more used in class functions, because the conversion and comparison of base types may be used in functions. In this case, it is necessary to use the functions that come with the wrapper type, and reduce the mixing of base types and wrapper types. Operation time of unpacking and sealing in use

Guess you like

Origin blog.csdn.net/weixin_42505381/article/details/128229279