016-Use of packaging

Disclaimer: All my articles are the compilation of online teaching videos, including Mad God Talk, Shang Silicon Valley, Dark Horse Programmer, etc., used as reference materials, without any commercial use, please refer to the majority of netizens, please do not spray ,Thank you. (Note that due to the website, some code characters may have problems. It is recommended that when reading the code, it is best to correspond with the picture below)
1. In Java, define the corresponding reference type for the eight basic data types— -Packaging class (encapsulation class), with the characteristics of the class, you can call the method in the class, Java is the real object-oriented.
016-Use of packaging
2. The basic data types are packaged into the instance of the packaging class (boxing).
1. Realized by the constructor of the packaging class:
int i = 500; Integer t = new Integer(i);
2. The packaging class can also be constructed through string parameters Object:
Float f = new Float("4.56");
Long l = new Long("asdf"); //NumberFormatException
3. Obtain the basic type variables of the package in the package object (unboxing) and
call the .xxxValue( of the package class ) Method:
boolean b = bObj.booleanValue();
After JDK1.5, automatic boxing and automatic unboxing are supported, but the types must match.
Fourth, the string is converted into a basic data type
1. Realized by the constructor of the packaging class:
int i = new Integer("12");
2. Through the parseXxx(String s) of the packaging class:
Float f = Float.parseFloat(" 12.1”);
Five, basic data types are converted into strings
1. Call the valueOf() method of string overload:
String fstr = String.valueOf(2.34f);
2. A more direct way:
String intStr = 5 + “”;
6. Example
int i = 500;
Integer t = new Integer(i);//Boxing, making a basic data type of data into the class
String s = t.toString(); //s=”500”, t is the class, there is a toString method
String s1 = Integer .toString(314); //s1=”314” Convert a number to a string
String s2 = “4.56”;
double ds = Double.parseDouble(s2); //Convert a string to a number
int j = t.intValue (); //j=500, intValue takes out the data
packaging class in the package class. The most used in actual development is that the string becomes the basic data type
String str1 = "30";
String str2 = "30.3";
int x = Integer.parseInt(str1);
float f = Float.parseFloat(str2);

Guess you like

Origin blog.51cto.com/12859164/2553816