byte與char的區別

 byte 是字節數據類型 ,是有符號型的,佔1 個字節;大小範圍爲-128—127 。char 是字符數據類型 ,是無符號型的,佔2字節(Unicode碼 );大小範圍 是0—65535 ;char是一個16位二進制的Unicode字符,JAVA用char來表示一個字符 。

下面用實例來比較一下二者的區別:

1、Char是無符號型的,可以表示一個整數,不能表示負數;而byte是有符號型的,可以表示-128—127 的數;如:

char c = (char) -3; // char不能識別負數,必須強制轉換否則報錯,即使強制轉換之後,也無法識別
System.out.println(c);
byte d1 = 1;
byte d2 = -1;
byte d3 = 127; // 如果是byte d3 = 128;會報錯
byte d4 = -128; // 如果是byte d4 = -129;會報錯
System.out.println(d1);
System.out.println(d2);
System.out.println(d3);
System.out.println(d4);

輸出結果爲:

?
1
-1
127
-128

2、char可以表中文字符,byte不可以,如:

char e1 = '中', e2 = '國';
byte f= (byte) '中';    //必須強制轉換否則報錯
System.out.println(e1);
System.out.println(e2);
System.out.println(f);

輸出結果爲:



45

3、char、byte、int對於英文字符,可以相互轉化,如:

byte g = 'b';    //b對應ASCII是98
char h = (char) g;
char i = 85;    //U對應ASCII是85
int j = 'h';    //h對應ASCII是104
System.out.println(g);
System.out.println(h);
System.out.println(i);
System.out.println(j);

輸出結果爲:

98
b
U
104

發佈了98 篇原創文章 · 獲贊 20 · 訪問量 5萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章