概述

Java提供了两个类型系统,基本类型与引用类型,使用基本类型在于效率,然而很多情况,会创建对象使用,因为对象可以做更多的功能,如果想要我们的基本类型像对象一样操作,就可以使用基本类型对应的包装类,如下:

基本类型 对应的包装类(位于java.lang包中)
byte Byte
short Short
int Integer
long Long
float Float
double Double
char Character
boolean Boolean

装箱与拆箱

基本类型与对应的包装类对象之间,来回转换的过程称为”装箱“与”拆箱“:

  • 装箱:从基本类型转换为对应的包装类对象。
  • 拆箱:从包装类对象转换为对应的基本类型。

用Integer与 int为例:(看懂代码即可)
基本数值——>包装对象

  1. public class test {
  2. public static void main(String[] args) {
  3. Integer i = new Integer(1);
  4. System.out.println(i);
  5. Integer ii = Integer.valueOf(2);
  6. System.out.println(ii);
  7. }
  8. }

包装对象——>基本数值

public class test {
    public static void main(String[] args) {
        Integer i = new Integer(4);
        int num = i.intValue();
        System.out.println(num);
    }
}

自动装箱与自动拆箱

由于我们经常要做基本类型与包装类之间的转换,从Java 5(JDK 1.5)开始,基本类型与包装类的装箱、拆箱动作可以自动完成。

public class test {
    public static void main(String[] args) {
        Integer i = 4;
        i = i + 5;
        System.out.println(i);
    }
}

基本类型与字符串之间的转换

基本类型转换为String

基本类型转换String总共有三种方式

public class test {
    public static void main(String[] args) {
        int i = 100;
        String s1 = i + "";
        System.out.println(s1 + 100);

        String s2 = Integer.toString(200);
        System.out.println(s2 + 100);

        String s3 = String.valueOf(300);
        System.out.println(s3 + 100);
    }
}

String转换成对应的基本类型
除了Character类之外,其他所有包装类都具有parseXxx静态方法可以将字符串参数转换为对应的基本类型:

  • public static byte parseByte(String s):将字符串参数转换为对应的byte基本类型。
  • public static short parseShort(String s):将字符串参数转换为对应的short基本类型。
  • public static int parseInt(String s):将字符串参数转换为对应的int基本类型。
  • public static long parseLong(String s):将字符串参数转换为对应的long基本类型。
  • public static float parseFloat(String s):将字符串参数转换为对应的float基本类型。
  • public static double parseDouble(String s):将字符串参数转换为对应的double基本类型。
  • public static boolean parseBoolean(String s):将字符串参数转换为对应的boolean基本类型。
    public class test {
      public static void main(String[] args) {
          int i = Integer.parseInt("100");
          System.out.println(i);
      }
    }