Difference between Java int and integer:
The difference between int and integer is the difference between basic data types and their wrapper classes:
int is a basic type, which directly stores the value, while integer is an object, pointing to this object with a reference
1. The data types in Java are divided into basic data types and complex data types
int is the former and integer is the latter (that is, a class); therefore, when the class is initialized, the variable of the int class is initialized to 0. The variable of Integer is initialized to null.
2. Initialization:
int i =1; Integer i = new Integer(1); (Treat integer as a class); but because of automatic packing and unboxing
Make it possible to use the Integer class: Integer i= 1;
int is a basic data type (for the traces left by the process, but a useful supplement to Java). Integer is a class, an extension of int, and defines many conversion methods.
Similar to: float Float;double Double;string String, etc., and also provides some other constants and methods that are very useful when dealing with int types.
For example: When you need to put things into ArrayList and HashMap, built-in types like int and double cannot be placed in, because the containers are all loaded with object, so these built-in types are required.
Each built-in type in Java has a corresponding overlay class.
The relationship between int and Integer in Java is relatively subtle. The relationship is as follows:
1.int is the basic data type;
2.Integer is an encapsulation class of int;
3. Both int and Integer can represent a certain value;
4.int and Integer cannot be used interchangeably because they have two different data types;
Give an example
ArrayList al=new ArrayList(); int n=40; Integer nI=new Integer(n); al.add(n);//No al.add(nI);//Yes
In addition, int is not supported when defining generics: For example: List<Integer> list = new ArrayList<Integer>(); Yes, but List<int> list = new ArrayList<int>(); No
In short: if we define an int type number and just use it to perform some addition, subtraction, multiplication and division operations as parameters to pass it, then we can directly declare it as the int basic data type, but if we want to
To handle the same object, you need to use Integer to declare an object. Because Java is an object-oriented language, it can provide many ways to convert between objects when declared as an object, which is similar to some commonly used
method. I think Java is an object-oriented language. When declaring a variable, it is best to declare it as an object format, which is more conducive to your understanding of object-oriented.
Thank you for reading, I hope it can help you. Thank you for your support for this site!