[Java Interview] The difference between basic data types and wrapper classes, how to choose?

Interviewer: Tell me about the difference between basic data types and wrapper classes, when to use wrapper classes and when to use basic data types.

OK,

  1. The most essential difference: the basic data type is not an object, and the packaging type is an object
  2. The storage location is different: the basic type is to directly store the variable value in the stack, while the wrapping type is to put the object in the heap and then use it by reference
  3. The initial value of the basic type such as int is 0, boolean is false, and the initial value of the package type is null;
  4. Objects of wrapper classes can be put into collections but primitive data types cannot

insert image description here

Alibaba Development Manual:
[Mandatory] The usage standards for basic data types and wrapper data types are as follows:
1) All POJO class attributes must use wrapper data types.
2) The return value and parameters of the RPC method must use the wrapping data type.
3) It is recommended to use basic data types for all local variables.
Explanation: There is no initial value for POJO class attributes to remind users that they must explicitly assign values ​​when they need to use them. Any NPE (null pointer exception) problems or storage inspections are guaranteed by users.
Positive example: The query result of the database may be null, because of automatic unboxing, receiving with basic data types has the risk of NPE.
Counter-example: The transaction report of a certain business shows the ups and downs of the total transaction amount, that is, plus or minus x%, where x is the basic data type, and when the call to the HSF service fails, the default value is returned, and the page displays: 0%, which means It is unreasonable and should be displayed as a dash -. Therefore, the null value of the packaging data type can represent additional information, such as: remote call failure, abnormal exit.

Guess you like

Origin blog.csdn.net/huhuhutony/article/details/120824973