Java Integer类
int型的包装类Integer
装箱
就是将基本数据类型转换为包装类.
拆箱
就是将包装类转换为基本数据类型.
Byte,Short,Integer和Long类包含的方法基本相同
Integer类的常用方法:
1. public static int parseInt(@NotNull String s)
//将字符串s解析成int类型的数据
2. public static Integer valueOf(@NotNull String s)
//返回保存指定的String值的Integer对象
3. public boolean equals(@Nullable Object obj)
//比较此对象与指定的对象是否相等
4. public int intValue()
//以int型返回此Integer对象
5. public short shortValue()
//以short型返回此Integer对象
6. public byte byteValue()
//以byte型返回此Integer对象
7. public static String toBinaryString(int i)
//以二进制无符号整数形式返回一个整数参数的字符串表示形式
8. public static String toOctalString(int i)
//以八进制无符号整数形式返回一个整数参数的字符串表示形式
9. public static String toHexString(int i)
//以十六进制无符号整数形式返回一个整数参数的字符串表示形式
10. public static String toString(int i,int radix)
//以radix进制的形式返回一个整数参数i的字符串表示形式
11. public int compareTo(@NotNull Integer anotherInteger)
//在数字上比较两个Integer对象.如果这两个值相等则返回0;如果调用对象的数值小于anotherInteger的数值则返回-1;大于则返回1
Integer类的常量:
MAX_VALUE:表示int类型可取的最大值,即2^31-1
MIN_VALUE:表示int类型可取的最小值,即-2^31
SIZE:int的二进制位数
TYPE:表示int的Class实例
public class Text{
public static void main(String[] args) {
int num=Integer.parseInt("123"); //将字符串转换为int类型
Integer iNum=Integer.valueOf("123"); //返回保存指定的String值的Integer对象
System.out.println("int数据与Integer对象的比较:"+iNum.equals(num));
String str1=Integer.toBinaryString(num); //获取数字的二进制表示
String str2=Integer.toOctalString(num); //获取数字的八进制表示
String str3=Integer.toHexString(num); //获取数字的十六进制表示
String str4=Integer.toString(num,12); //获取数字的十二进制表示
System.out.println("123的二进制表示为:"+str1);
System.out.println("123的八进制表示为:"+str2);
System.out.println("123的十六进制表示为:"+str3);
System.out.println("123的12进制表示为:"+str4);
//由基本数据类型到相应类对象的转换称为"自动装箱",反之称为"自动拆箱"
Integer a=12; //自动装箱
int b=a; //自动拆箱
int c=a.intValue(); //转化为基本数据类型int
short s=a.shortValue(); //转换为基本数据类型short
byte t=a.byteValue(); //转换为基本数据类型byte
System.out.println("a="+a); //自动拆箱为int型并输出
System.out.println("c="+c+" s="+s+" t="+t);
System.out.println(Integer.valueOf("122").compareTo(Integer.valueOf("100")));
System.out.println("int类型可取的最大值:"+Integer.MAX_VALUE);
System.out.println("int类型可取的最小值:"+Integer.MIN_VALUE);
System.out.println("int型的二进制位数:"+Integer.SIZE);
System.out.println(Integer.TYPE);
}
}
/*int数据与Integer对象的比较:true
123的二进制表示为:1111011
123的八进制表示为:173
123的十六进制表示为:7b
123的12进制表示为:a3
a=12
c=12 s=12 t=12
1
int类型可取的最大值:2147483647
int类型可取的最小值:-2147483648
int型的二进制位数:32
int*/