Home >Java >javaTutorial >wrapper class for primitive main data type
JAVA has prepared a wrapper class for each primitive main data type (except char) after version 5.0,
int→Integer; long→Long; byte→Byte; short→Short; float→Float;
double→Double ;boolean→Boolean;
What is the function of packaging class?
The function of a wrapper class is to pass a value into the constructor of the wrapper class, so that an object of the wrapper class can be created. Moreover, the packaging class also has the functions of automatic boxing and automatic unpacking.
The following only uses Integer as an example, for example:
Integer d=3; //Autoboxing, that is, you can use int values to construct an object and point to a reference variable.
int d=new Integer(123);//Automatically unpack and assign the instance variable value of the object directly to the int type variable.
Of course it’s not just these uses.
You can also directly add int type variables when adding elements to ArrayListc0f559cc8d56b43654fcbe4aa9df7b4a;
If the parameters of some methods are a certain packaging type, you can directly pass in the corresponding primitive main data type; the return value of the method is the same Yes;
There are also conditional judgment statements, which can also be judged using Boolean references.
Of course it can also be used during numerical operations:
int a=new Integer (2) + 3; // can also be run.
What needs special attention is a little knowledge about the automatic boxing of Integer,
Integer a=new Integer(127); Integer b=(127); System.out.println(a==b); System.out.println(a.equals(b));
The result is false, true. But when
Integer c=127; Integer d=127; System.out.println(a==b); System.out.println(a.equals(b));
the result is true, true.
This situation occurs because, during autoboxing, if the value passed in when creating an Integer object is less than 128, and the second object is created and is equal to the value passed in the first object, then the second The application variable of the object will directly point to the first object created, without creating a new object.
There are generally methods in classes, and there are many methods to use in the wrapper classes defined by java.
Let’s take Integer as an example to list some important static methods, that is, methods that can be called directly with Integer.
Decode a string into an instance variable value in Integer, decode (String st)
Parse a string into an int value, Integer.parseInt(String,int);//String is the incoming numeric character String, int is the base of the passed in string, this method returns a decimal int value, for example:
System.out.println(d.parseInt("4d", 16));
The return is 77.
You can also turn it over and convert int or Integer into String:
int e=3; or Integer.toString(new Integer(22));
Integer.toString(e);
There are many other methods , for details, you can view the java.lang.Integer class in the API. This is also true for several other packaging categories.