包裝類———Integer
Integer 類在對象中包裝了一個基本類型int的值。Integer類型的對象包含一個 int 類型的字段。此外,該類提供了多個方法,能在 int 類型和 String 類型之間互相轉換,同時還提供了其他一些處理int類型時非常有用的常量和方法。
1.構造方法
Integer類有兩種構造方法
1.Integer(int number)
該方法以一個int型變量作為參數來獲取Integer對象。
例:
Intrger number = new Integer(7);
2.Integer(String str)
該方法以一個String型變量作為參數來獲取Integer對象。
例:
Intrger number = new Integer("45");
*要用數值型String變量作為參數,如123,否則將會拋出NumberFormatException異常。
在代碼中例子:
package com.integer;
public class integer {
public static void main(String[] args){
// 方式1 Integer(int number)
int i=100;
Integer a = new Integer(i);
System.out.println("a:"+a);
//方式2 Integer(String str)
String s = new String("100");
/*
* NumberFormatException
* String s = new String("abc");
*/
Integer b=new Integer(s);
System.out.println("b:"+b);
}
}
運行結果:
a:100
b:100
2.常用方法
1.Integer類的常用方法如下
2.Integer類中的parseInt()方法返回與調用該方法的數值字符串相應的整型(int)值
例:
public class Summation { // 創建類Summation
public static void main(String args[]) { // 主方法
String str[] = { "89", "12", "10", "18", "35" }; // 定義String數組
int sum = 0; // 定義int型變量sum
for (int i = 0; i < str.length; i++) { // 循環遍歷數組
int myint=Integer.parseInt(str[i]);//將數組中的每個元素都轉換為int型
sum = sum + myint; // 將數組中的各元素相加
}
System.out.println("數組中的各元素之和是:" + sum); // 將計算后結果輸出
}
}
運行結果:
數組中各元素之和是:164
3.Integer類的toString()方法,可將Integer對象轉換為十進制字符串表示。toBinaryString()、toHexString()和toOctalString()方法分別將值轉換成二進制、十六進制和八進制字符串。
例:
public class Charac { // 創建類Charac
public static void main(String args[]) { // 主方法
String str = Integer.toString(456); // 獲取數字的十進制表示
String str2 = Integer.toBinaryString(456); // 獲取數字的二進制表示
String str3 = Integer.toHexString(456); // 獲取數字的十六進制表示
String str4 = Integer.toOctalString(456); // 獲取數字的八進制表示
System.out.println("'456'的十進制表示為:" + str);
System.out.println("'456'的二進制表示為:" + str2);
System.out.println("'456'的十六進制表示為:" + str3);
System.out.println("'456'的八進制表示為:" + str4);
}
}
運行結果:
'456'的十進制表示為:456
'456'的二進制表示為:111001000
'456'的十六進制表示為:1c8
'456'的八進制表示為:710
3.常量
Integer類提供了以下4個常量.
1.MAX_VALUE:表示int類型可取的最大值,即2^(31)-1。
2.MIN_VALUE:表示int類型可取的最小值,即-2^31。
3.SIZE:用來以二進制補碼形式表示int值的位數。
4.TYPE:表示基本類型int的Class實例。
例:
public class GetCon { // 創建類GetCon
public static void main(String args[]) { // 主方法
int maxint = Integer.MAX_VALUE; // 獲取Integer類的常量值
int minint = Integer.MIN_VALUE;
int intsize = Integer.SIZE;
System.out.println("int類型可取的最大值是:" + maxint); // 將常量值輸出
System.out.println("int類型可取的最小值是:" + minint);
System.out.println("int類型的二進制位數是:" + intsize);
}
}
運行結果:
int類型可取的最大值是:2147483647
int類型可取的最小值是:-2147483648
int類型的二進制位數是:32