Android基础Java 基础

Java 常用类 04. Java 包装类

2021-12-16  本文已影响0人  yjtuuige

包装类

基本数据类型 包装类型
byte Byte
short Short
int Integer
long Long
float Float
double Double
boolean Boolean
char Character

装箱与拆箱

package com.base.demo04;

public class Test01 {
    public static void main(String[] args) {
        // 装箱, 基本类型 → 引用类型
        // 基本类型
        int num1 = 18;
        // 使用 Integer 类创建对象
        Integer integer1 = new Integer(num1);
        Integer integer2 = Integer.valueOf(num1);

        // 拆箱, 引用类型 → 基本类型
        Integer integer3 = new Integer(100);
        int num2 = integer3.intValue();

        // 上述为 jdk1.5 之前方法,之后提供了自动装箱、拆箱
        int age = 30;
        // 自动装箱
        Integer integer4 = age;
        System.out.println(integer4);
        // 自动拆箱
        int age2 = integer4;
        System.out.println(age2);
    }
}

应用

基本类型和字符串之间转换

注意:需保证类型兼容,否则抛出 NumberFormatException 异常

int n1 = 10;
// 1. 使用+号
String s1 = n1 + "";
// 2. 使用 Integer 中的toString() 方法
String s2 = Integer.toString(n1);
String s3 = Integer.toString(n1, x);   //  x 为进制要求
String str = "150";    // String 转基本数据类型,字符串不能包含非数字
// 使用Integer.parseXXX();
int n2 = Integer.parseInt(str);

// boolean 字符串形式转成基本类型,"true" ---> true 非 “true" ———> false
String str2 = "true";
boolean b1 = Boolean.parseBoolean(str2);

总结

上一篇下一篇

猜你喜欢

热点阅读