Java包裝類介紹與類型之間相互轉換


1、包裝類存在的意義

通俗解釋就是由於Java是面對對象的語言,而基本類型不具有面對對象的概念,為了彌補不足,引入了包裝類方便使用面對對象的變成思想操作基本類型。

2、基本類型和包裝類對應關系

byte

Byte

int

Integer

short

Short

long

Long

float

Float

double

Double

boolean

Boolean

char

Character

注:String不是基本類型,所以不存在包裝類的概念。很多初學者容易混淆這個概念。

3、包裝類的使用

以Integer類為例,其它類可以翻閱API文檔查閱:

 1     public static void main(String[] args) {  2         Integer i = new Integer(5);// 通過構造函數把int類型轉換為Integer類型。
 3         Integer j = new Integer("5");// 通過構造函數把String類型的數值轉為int類型后再轉為Integer類型,如果String中不包含數值,則會出現異常。
 4         int temp = 10;  5         Integer m = temp;// 自動裝箱
 6         Integer n = new Integer(temp);// 自動裝箱
 7         int x = m.intValue();// 手動拆箱
 8         int y = n;// 自動拆箱
 9         System.out.println(i + "\t" + j + "\t" + m + "\t" + n + "\t" + x + "\t" + y); 10     }

運行結果:

5    5    10    10    10    10

4、基本類型與包裝類轉換為String

a、使用toString轉換

1     public static void main(String[] args) { 2         int i = 50; 3         String str = Integer.toString(i);//自動裝箱並調用toString()方法,這也是將基本類型轉換為包裝類的好處。
4  System.out.println(str); 5     }

運行結果:

50

b、使用valueOf轉換

1     public static void main(String[] args) { 2         String str = String.valueOf("10"); 3  System.out.println(str); 4     }

運行結果:

10

c、數字+""方法

1     public static void main(String[] args) { 2         int i = 100; 3         String str = i + ""; 4  System.out.println(str); 5     }

運行結果:

100

 5、包裝類轉換為基本類型

1     public static void main(String[] args) { 2         Integer i = new Integer("20"); 3         int m = i.intValue(); 4  System.out.println(m); 5     }

運行結果:

20

6、字符串轉換為基本類型

1     public static void main(String[] args) { 2         int i = Integer.parseInt("50"); 3  System.out.println(i); 4     }

運行結果:

50


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM