The contrast between Java int and integer

  • 2020-05-30 20:04:49
  • OfStack

Java int and integer:

The big difference between int and integer is the difference between the base data type and its wrapper class:

int is a primitive type that stores values directly, while integer is an object that points to it with a reference

1. 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 int class is initialized to 0. While the variable of Integer is initialized to null.

2. Initialization:

int i = 1; Integer i = new Integer (1); (think of integer as a class); But thanks to autoboxing and unboxing

Makes it available to the Integer class: Integer i= 1;

int is the basic data type (process-oriented traces, but a useful complement to java), and Integer is a class that is an extension of int and defines a number of transformation methods

Similarly: float Float; double Double; string String et al., but also provides some other constants and methods that are useful when dealing with int types

For example, when you need to put something into ArrayList, HashMap, the built-in types int, double don't fit, because the containers are all object, so you need an overlay of these built-in types.

Each built-in type in Java has a corresponding enclosing class.

In Java, the relationship between int and Integer is more subtle. The relationship is as follows:

1.int is the basic data type;

2.Integer is the encapsulation class of int;

3. Both int and Integer can represent a certain value;

4.int and Integer are not interoperable because of their two different data types;

For example


 ArrayList al=new ArrayList();

  int n=40;

  Integer nI=new Integer(n);

  al.add(n);// Can not be 

  al.add(nI);// can 

And the generic definition does not support int: e.g. List < Integer > list = new ArrayList < Integer > (a); Can the List < int > list = new ArrayList < int > (a); Are not

All in all: if we define a number of type int, just to do some addition, subtraction, multiplication and division, and or is passed as a parameter, then we can declare int as the basic data type, but if we want to be like

If object 1 is to be processed, then Integer should be used to declare an object. Because java is an object-oriented language, it can provide many ways to convert objects when declaring as objects

Methods. Since java is an object-oriented language, it is better to declare one variable as an object format, which is more conducive to your understanding of object orientation.

Thank you for reading, I hope to help you, thank you for your support of this site!


Related articles: