Small knowledge, big challenge! This article is participating in the creation activity of “Essential Tips for Programmers”.
The problems encountered in the development of before: in the statement, an entity class, some variables with int some Integer, some with long some long, was also compared meng that are both represent int in use from time to tome what difference? There’s a big difference. This is just one of the minor issues we encountered during development to talk about the relationship and difference between wrapper types and base types
1. Packaging type and basic type
- Basic data types
There are eight basic data wrapper types: Boolean, byte, char, short, int, long, float, and double
- Wrapper types (these basic data types correspond under java.lang)
A simple type | boolean | byte | char | short | Int | long | float | double |
---|---|---|---|---|---|---|---|---|
Binary digit | 1 | 8 | 16 | 16 | 32 | 64 | 32 | 64 |
Packing type | Boolean | Byte | Character | Short | Integer | Long | Float | Double |
Basic data types and their corresponding wrapper types can be converted to each other. Take int and Integer for example:
Turn int Integer
int a=3; Integer A = new Integer(a); // Create instance with new or Integer A = integer.valueof (A); // Created by static method valueOf(int)Copy the code
Turn the Integer int
Integer A = Integer.valueOf(5);
int a=A.intValue();
Copy the code
2. Automatic packing and unpacking
We don’t convert int to Integer or Integer to int when we write code, we just assign: ‘
Integer A = 18; Int B = A; // Automatic unpackingCopy the code
Autoboxing: Assigning a base type to a reference variable automatically “wraps” it into its corresponding wrapper class and unboxing it the same way
3. The difference between
I have encountered a similar situation in the development process: when creating an entity class, suppose that an attribute is count, if declared by Integer, when stored in the database, if no value is specified, then the database will store NULL. If declared by int, when stored in the database, if no value is specified, then the database will store 0. This also means that the specific statement for int or Integer need to see the actual situation of specific, if need to remove the value judgment, null is also consider whether this need to decide (indicating packing type and basic types of the initial value is different) difference, of course, there are many, I’m here just to share both the initial value is different, There are other differences you can search for