Interger包装类

Integer 包装类在对象中包装了一个基本类型 int 的值。Integer 类型的对象包含一个 int 类型的字段。该类提供了多个方法,能在 int 类型和 String 类型之间互相转换,我们可以通过调用这些方法在int类型和String类型之间进行转换。

说到int 类型和 String 类型之间互相转换,那么如何转换呢?

可以看下面的代码实例:

public class IntegerTest1 {
public static void main(String []args){
	int num=9;
	//int类型转换为String类型
	//方法1:最简单最常用的
	String s=num+"";
	System.out.println(s);
	//方法2:通过创建Integer对象来转换
	Integer in =new Integer(num);
	String s1=in.toString();//调用了Integer.toString()的方法,将Integer对象转换为字符串对象
	System.out.println(s1);
	//方法3:
	String.valueOf(num);//通过调用String.valueOf()方法进行转换
	//方法4:直接定义一个值为整数的字符串类型
	String s2="9";
	System.out.println(s2);
	//String类型转换为int类型
	//方法1:注意String对象内的参数值必须是整数
	String s3="12";
	Integer in1= new Integer(s3);
	int num1=in1.intValue();
	System.out.println(num1);
	//方法2:
	int num2=in1.parseInt(s3);
	System.out.println(num2);
}
}

Integer还能把一个int类型的十进制整数转为二进制、八进制、十六进制

public class IntegerTest {
	public static void main(String[] args) {
		// public static String toBinaryString(int num)
		System.out.println(Integer.toBinaryString(100));//十进制转二进制
		// public static String toOctalString(int num)
		System.out.println(Integer.toOctalString(100));//十进制转八进制
		// public static String toHexString(int num)
		System.out.println(Integer.toHexString(100));//十进制转十六进制
 
		// public static final int MAX_VALUE
		System.out.println(Integer.MAX_VALUE);//输出integer对象的最大值
		// public static final int MIN_VALUE
		System.out.println(Integer.MIN_VALUE);//输出integer对象的最小值
		System.out.println(Integer.bitCount(100));//统计100转换为二进制后1的个数
	}

}

还有一个要注意的点就是Integer对象不能随意的用"=="号;

下面代码有详细解释:

/**
 * 注意:Integer的数据直接赋值,如果在-128到127之间,会直接从缓冲池里获取数据,而不是新建一个Integer对象
 * @author 哎呦不错呦
 *
 */
public class IntegerTest2 {
public static void main(String []args){
	//如果是两个int类型的对象,会直接比较它们的值
	int num1 = 50;
	int num2 = 50;
	System.out.println("num==num2:"+(num1==num2));//返回的是true
	
	//当我们对两个包装类型比较时,还有一种情况,就是不通过new来创建Integer,而是通过JVM自动把int基础类型转换成Integer对象(下面称为封包)。
	//Integer的数据直接赋值,如果在-128到127之间,会直接从缓冲池里获取数据,而不是新建一个Integer对象
	Integer in=26;
	Integer in1=26;
	System.out.println("in==in1:"+(in==in1));//返回true
	
	//当我们对两个包装类型比较时,还有一种情况,就是不通过new来创建Integer,而是通过JVM自动把int基础类型转换成Integer对象(下面称为封包)。
	//Integer的数据直接赋值,如果在-128到127之间,会直接从缓冲池里获取数据,而不是新建一个Integer对象
	Integer in5=128;
	Integer in6=128;
	System.out.println("in5==in6:"+(in5==in6));//返回false
	
	//当我们对两个包装类型比较时,JVM通过比较他们的地址来判断是否是同一个对象。他们只是拥有相同value值的Integer对象。
	Integer in2=new Integer(50);
	Integer in3=new Integer(50);
	System.out.println("in2==in3:"+(in2==in3));//返回的是false
	
	//当我们把一个Integer和一个int类型对象比较时,是通过从Integer对象取出value值和int类型值比较
	Integer in4=127;
	int num3=123;
	System.out.println("in4==num3:"+(in4==num3));//返回的是false	
}
}

猜你喜欢

转载自blog.csdn.net/coder150806/article/details/83105873