[Java] Automatic unboxing and automatic boxing

Automatic boxing and automatic unboxing are functions provided by JDK1.5. Auto-boxing is to directly assign a basic type of data to the corresponding packaging type; automatic unboxing is to directly assign an object of a packaging type to the corresponding basic type; through the automatic boxing and unboxing functions, the basic type can be greatly simplified The conversion process between variables and wrapper class objects.

Java is a very pure object-oriented programming language, and its design philosophy is "everything is an object" . But the 8 basic data types do not have the characteristics of objects. The reason why Java provides 8 basic data types is mainly to take care of the traditional habits of programmers. Although these 8 basic data types do bring some convenience, they are also subject to some restrictions at certain times. For example, all reference type variables inherit from the Object class and can be used as Object type variables, but basic data types cannot. If a method expects a parameter of type Object, but the actual value passed in is a number, special handling is required. With wrapper classes, this kind of problem can be simplified. Different wrapper classes are not directly comparable, this includes:

  • Can't use == for direct comparison because they are different data types
  • It cannot be converted to a string for comparison, because after converting to a string, the floating point value has a decimal, and the integer value does not
  • They cannot be compared using the compareTo method, although they have a compareTo method, but this method can only compare the same type. The packaging classes of integer and floating-point types are all inherited from the Number type, and the Number type defines methods for converting numbers to byte, short, int, long, float, and double respectively. So you can convert Integer and Double to the same basic data type (such as double) and then use == to compare

Guess you like

Origin blog.csdn.net/Your_Boy_Tt/article/details/130314646