Base type wrapper class

The base type wraps the role of the class

The advantage of encapsulating a basic data type as an object is that you can define more functional methods in the object to manipulate that data

One of the common operations: used to convert primitive data types to and from strings

 

The wrapper class corresponding to the base type

Basic data types A wrapper class
byte Byte
short Short
int Integer
long Long
float Float
double Double
char Character
boolean Boolean 

 

The Integer class

Summary of the Integer class

Wraps the value of the primitive int in an object

The method name instructions
public Integer(int value) Create an Integer object from an int value (obsolete)
public Integer(String s) Create an Integer object from a String value (obsolete)
public static Integer valueOf(int i) Returns an Integer instance representing the specified int value
public static Integer valueOf(String s) Returns an Integer object String holding the specified value
Integer in1=Integer.valueOf("123"); Integer in2=Integer.valueOf(123); Integer in3=new Integer(123); // Obsolete Integer in4=new Integer("123"); // Obsolete Integer in5=in3+in2; System.out.println(in1); System.out.println(in2); System.out.println(in3); System.out.println(in4); System.out.println(in5);Copy the code

Output:

123

123

123

123

246

Automatic unpacking and automatic packing

Automatic packing

Converts the base data type to the corresponding wrapper class type

 

Automatic unpacking

Converts the wrapper class type to the corresponding base data type

Integer i = 100; I += 200; // i = i + 200; I + 200 automatic unpacking; i = i + 200; It's automatic packingCopy the code

A conversion between int and String

Int is converted to String

Transformation way

Method 1: Directly add an empty string after the number

Method 2: Static valueOf()

int number = 100; String s1 = number + "";Copy the code
int a=123; String b= string.valueof (a);Copy the code

String is converted to int

Transformation way

Method 1: Convert the string number to an Integer and then call the valueOf() method

Method 2: Use the Integer static method parseInt() to convert

‐‐ int String s = "100"; // Mode 1: String ‐‐ Integer ‐‐ int Integer I = integer.valueof (s); //public int intValue() int x = i.intValue(); System.out.println(x); Public static int parseInt(String s) int y = integer.parseInt (s); System.out.println(y);Copy the code

String data sort example

Case needs

There is a string: “91 27 46 38 50”, please write a program to implement the final output: 27 38 46 50 91

String num="91 27 46 38 50"; String[] number=num.split(" "); int ans[]=new int[number.length]; for(int i=0; i<number.length; i++){ int numb=Integer.parseInt(number[i]); ans[i]=numb; } Arrays.sort(ans); for (int i = 0; i < ans.length; i++) { System.out.println(ans[i]); }Copy the code