Integer 类对象包含一个 int 类型的字段。此外,该类提供了多个方法,能在 int 类型和 String 类型之间互相转换,还提供了处理 int 类型时非常有用的其他一些常量和方法。
Integer 类的构造方法
- Integer(int value):构造一个新分配的 Integer 对象,它表示指定的 int 值。
- Integer(String s):构造一个新分配的 Integer 对象,它表示 String 参数所指示的 int 值。
- Integer integer1 = new Integer(100);
- Integer integer2 = new Integer("100");
Integer 类的常用方法
在 Integer 类内部包含一些和 int 类型操作有关的方法,表 1 列出了这些常用的方法。
表 1 Integer类中的常用方法
| 方法 | 返回值 | 功能 |
| byteValue() |
byte |
以 byte 类型返回该 Integer 的值 |
| shortValue() |
short |
以 short 类型返回该 Integer 的值 |
| intValue() |
int |
以 int 类型返回该 Integer 的值 |
| toString() |
String |
返回一个表示该 Integer 值的 String 对象 |
| equals(Object obj) |
boolean |
比较此对象与指定对象是否相等 |
compareTo(Integer anotherlnteger) |
int |
在数字上比较两个 Integer 对象,如相等,则返回 0; 如调用对象的数值小于 anotherlnteger 的数值,则返回负值; 如调用对象的数值大于 anotherlnteger 的数值,则返回正值 |
| valueOf(String s) |
Integer |
返回保存指定的 String 值的 Integer 对象 |
| parseInt(String s) |
int |
将数字字符串转换为 int 数值 |
- String str = "456";
- int num = Integer.parseInt(str);
- int i = 789;
- String s = Integer.toString(i);
- public class Test {
- public static void main(String[] args) {
- int num = 40;
- String str = Integer.toString(num);
- String str1 = Integer.toBinaryString(num);
- String str2 = Integer.toHexString(num);
- String str3 = Integer.toOctalString(num);
- System.out.println(str + "的二进制数是:" + str1);
- System.out.println(str + "的八进制数是:" + str3);
- System.out.println(str + "的十进制数是:" + str);
- System.out.println(str + "的十六进制数是:" + str2);
- }
- }
40的二进制数是:101000
40的八进制数是:50
40的十进制数是:40
40的十六进制数是:28
Integer 类的常量
Integer 类包含以下 4 个常量。
- MAX_VALUE:值为 231-1 的常量,它表示 int 类型能够表示的最大值。
- MIN_VALUE:值为 -231 的常量,它表示 int 类型能够表示的最小值。
- SIZE:用来以二进制补码形式表示 int 值的比特位数。
- TYPE:表示基本类型 int 的 Class 实例。
- int max_value = Integer.MAX_VALUE;
- int min_value = Integer.MIN_VALUE;
- int size = Integer.SIZE;
- Class c = Integer.TYPE;
JAVA Integer类详解
原文:https://www.cnblogs.com/drigon/p/15029626.html