Java-Mutual conversion between basic data types, packaging classes, and String classes

1. Packaging
Java is an object-oriented programming language, but the basic data type is not an object, which is very inconvenient in the operation of sets, so we need to transform the basic data type into an object for operation and operation, this is the packaging class.
There are 8 basic data types and 8 packaging types.
Insert picture description here
Except for Character and Boolean directly inherited from the Object class, these 6 all inherit from the Number class, and the Number class then inherits from the Object class.
2. The mutual conversion between basic data types, packaging classes, and String classes.
Insert picture description here
Packing operation:

//基本数据类型 --> 包装类:调用包装类的构造器
    @Test
    public void test1() {
    
    
        int num1 = 10;
        Integer in1 = new Integer(num1);
        System.out.println(in1.toString());
        }

Unboxing operation:

//包装类 --> 基本数据类型:调用包装类的xxxValue()
    @Test
    public void test2() {
    
    
        Integer in1 = new Integer(12);
        int i1 = in1.intValue();
        System.out.println(i1 + 1);
        }

New features of JDK 5.0: In order to reduce the workload of programmers, it provides the function of automatic boxing and unboxing.

/*
     *  JDK 5.0新特性:自动装箱和自动拆箱
     */
    @Test
    public void test3(){
    
    
        //自动装箱:基本数据类型 --> 包装类
        int num = 10;
        Integer in1 =num;//自动装箱

        boolean b1 = true;
        Boolean b2 = b1;//自动装箱
        //自动拆箱:包装类 --> 基本数据类型
        System.out.println(in1.toString());

        int num1 = in1;//自动拆箱
    }
//基本数据类型、包装类 --> String类型:调用String重载的valueOf(Xxx xxx)
    @Test
    public void test4(){
    
    
        int num1 = 10;
        //方法一:
        String str1 = num1 + "";
        //方法二:
        float f1 = 12.3f;
        String str2 = String.valueOf(f1);
        }
//String类型 --> 基本数据类型、包装类:调用包装类的parseXxx()
    @Test
    public void test5(){
    
    
        String str1 = "123";
        //错误的情况:
//        int num1 = (int)str1;
//        Integer in1 = (Integer)str1;
        //可能会报NumberFormatException异常
        int n1 = Integer.parseInt(str1);
        System.out.println(n1 + 1);
        }

Guess you like

Origin blog.csdn.net/qq_30068165/article/details/114278974