Basic data types and their corresponding wrapper classes


The basic data type and its corresponding wrapper class conversion

(1) Basic data type –> wrapper class:

  • Automatic packing:
    Integer i = 9;
Copy the code
  • Using the valueOf() method of the wrapper class:
    Integer I = Integer.valueOf(3);
Copy the code

(2) Wrapper class –> Basic data type

  • Automatic unpacking:
    Integer I = 9;
    int i = I;
Copy the code
  • Use the xxxValue() method of the wrapper class:
    Integer I = 9;
    int i = I.intValue();
Copy the code

(3) Basic data type –>String:

  • Use the hyphen ‘+’ :
    int i = 9;
    String s = "" + i; 
Copy the code
  • Using the valueOf() method of String:
    int i = 9;
    String s = String.valueOf(i);
Copy the code

(4) String– > Basic data type:

  • Call the parseXxx(String s) method of the corresponding wrapper class:
    String s = "9";
    int a = Integer.parseInt(s);
Copy the code

(5) Wrapper class –>String:

  • Using the valueOf() method of String:
    Integer I = 9;
    String s = String.valueOf(I);
Copy the code
  • Call the toString() method of the object that wraps the corresponding class:
    Integer I = 9;
    String s = I.toString();
Copy the code
  • Call the toString() method of the corresponding wrapper class:
    Integer I = 9;
    String s = Integer.toString(I);
Copy the code

(6) String– > Wrapper class:

  • Call the parseXxx(String s) method of the corresponding wrapper class:
    String s = "9";
    Integer I = Integer.parseInt(s);
Copy the code

Note: A NumberFormatException error occurs when a String is converted to a primitive data type or wrapper class if the conversion is not possible. Such as:

    String s = "aaaa";
    Integer I = Integer.parseInt(s);
Copy the code