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


基本类型

对应的包装类(位于java.lang包中)

byte

Byte

short

Short

int

Integer

long

Long

float

Float

double

Double

char

Character

boolean

Boolean

Integer类

Integer类概述:包装一个对象中的原始类型 int 的值

Integer 类构造方法及静态方法

方法名

说明

public Integer(int value)

根据 int 值创建 Integer 对象 ( 过时 )

public Integer(String s)

根据 String 值创建 Integer 对象 ( 过时 )

public static Integer valueOf(int i)

返回表示指定的 int 值的 Integer 实例

public static Integer valueOf(String s)

返回一个保存指定值的 Integer 对象 String

public static void main(String[] args){
    //public Integer(intvalue):根据int值创建Integer对象(过时)
    Integer i1=new Integer(100);
    System.out.println(i1);
    //public Integer(Strings):根据String值创建Integer对象(过时)
    Integer i2=new Integer("100");
    //Integeri2=newInteger("abc");
    //NumberFormatException
    System.out.println(i2);
    System.out.println("--------");
    //public static Integer valueOf(inti):返回表示指定的int值的Integer实例
    Integer i3=Integer.valueOf(100);
    System.out.println(i3);
    //public static Integer valueOf(Strings):返回一个保存指定值的Integer对象String 
    Integer i4=Integer.valueOf("100");
    System.out.println(i4);
}

 装箱与拆箱

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

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

用 Integer 与 int 为例:



基本数值 ----> 包装对象



Integer i1=new Integer(4);//使用构造函数函数
Integer i2=Integer.valueOf(4);//使用包装类中的valueOf方法



包装对象 ----> 基本数值



int num=i.intValue();

 自动装箱与自动拆箱



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



Integer i=4;//自动装箱。相当于Integer i=Integer.valueOf(4);
i=i+5;//等号右边:将i对象转成基本数值(自动拆箱)i.intValue()+5;
//加法运算完成后,再次装箱,把基本数值转成对象。

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

基本类型转换为String

  • 转换方式
  • 1、直接在数字后面加一个空字符串
  • 2、通过String类静态方法valueOf()

示例代码:

public static void main(String[] args){
    //int---String
    int number=100;
    //方式1 
    String s1= number+"";
    System.out.println(s1);
    //方式2 
    //public static String valueOf(int i)
    String s2=String.valueOf(number);
    System.out.println(s2);
    System.out.println("--------");
}

String转基本类型



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



  • public static byte parseByte(String s):将字符串参数转换为对应的byte基本类型。
  • public static short parseShort(String s):将字符串参数转换为对应的short基本类型。
  • public static int parseInt(Strings):将字符串参数转换为对应的int基本类型。
  • public static long parseLong(Strings):将字符串参数转换为对应的long基本类型。
  • public static float parseFloat(Strings):将字符串参数转换为对应的float基本类型。
  • public static double parseDouble(Strings):将字符串参数转换为对应的double基本类型。
  • public static boolean parseBoolean(Strings):将字符串参数转换为对应的boolean基本类型。