java基础之Integer包装类

java基础之Integer包装类

Integer类概述:
Integer 类在对象中包装了一个基本类型 int 的值
该类提供了多个方法,能在 int 类型和 String 类型之间互相转换,还提供了处理 int 类型时非常有用的其他一些常量和方法
构造方法
public Integer(int value)

public Integer(String s)


类型转换:

int类型和String类型的相互转换
int – String
String – int
成员方法:
public int intValue()
public static int parseInt(String s)//重点
public static String toString(int i)
public static Integer valueOf(int i)
public static Integer valueOf(String s)

package Arrays;

public class IntegerDemo_1 {
	public static void main(String[] args) {
		
		//String->Integer
		String s = "123";
		Integer num = new Integer(s);
	/*	int类型和String类型的相互转换
		int – String
		String – int

		public int intValue()
		public static int parseInt(String s)//重点
		public static String toString(int i)
		public static Integer valueOf(int i)
		public static Integer valueOf(String s)*/
//		int->string
		//1.拼接
		int number = 100;
		String s1 = ""+number;
		//2.
		Integer num1 = new Integer(number);
		String s2 = num1.toString();
		//3
		String s3 = String.valueOf(number);
		
//      String->int
		
		String ss = "123";
		//1
		Integer n1 = new Integer(ss);
		 int nm1= n1.intValue();
		//2
		 int nm2 = Integer.parseInt(ss);
		
		
		
		
		
		
	}

}

新特性:

JDK1.5以后,简化了定义方式。
Integer x = new Integer(4);可以直接写成
Integer x = 4;//自动装箱。
x  = x + 5;//自动拆箱。通过intValue方法。

需要注意:
Integer iii = null;
iii += 1000;
System.out.println(iii);

在使用时,Integer  x = null;上面的代码就会出现NullPointerException。

package Arrays;

public class IntegerDemo_2 {
	public static void main(String[] args) {
		
		Integer n1 = new Integer(4);
		Integer n2 = 4;	//自动装箱
		int n3=n2;	//自动拆箱
		
		//小细节
		Integer n4 = null;
		//int n4 = 0;
		 n4+=1000;
		System.out.println(n4);	
		
	}

}
package Arrays;

public class IntegerDemo_2 {
    public static void main(String[] args) {
        
        Integer n1 = new Integer(4);
        Integer n2 = 4;    //自动装箱
        int n3=n2;    //自动拆箱
        
        //小细节
        Integer n4 = null;
        //int n4 = 0;
         n4+=1000;
        System.out.println(n4);    
        
    }

}






 缓冲池问题:
针对-128到127之间做了一个数据缓冲池,如果数据是该范围的,每次并不创建新空间。

Integer x = 128;
Integer y = 128;
syso(x==y);//false地址不一样