Java基本數據類型的裝換
Java基本數據類型的裝換順序如下所示:
低 ------------------------------------> 高
byte,short,char—> int —> long—> float —> double
由低到高裝換:Java基本數據類型由低到高的裝換是自動的.並且可以混合運算,必須滿足轉換前的數據類型的位數要低於轉換後的數據類型,例如: short數據類型的位數為16位,就可以自動轉換位數為32的int類型,同樣float數據類型的位數為32,可以自動轉換為64位的double類型 比如:
/**
* 基本數據類型的轉換
*
*/
public class Convert {
public static void main(String[] args) {
upConvert();
System.out.println("=====================我是分割線========================");
downConcert();
}
/**
* 向上轉換
*/
public static void upConvert(){
char c = 'a';
byte b = (byte) c;
short s = b;
int i = s;
long l = i;
float f = l;
double d = f;
System.out.println(c);
System.out.println(b);
System.out.println(s);
System.out.println(i);
System.out.println(l);
System.out.println(f);
System.out.println(d);
}
/**
* 向下轉換
*/
public static void downConcert(){
double d = 97.0;
float f = (float) d;
long l = (long) f;
int i = (int) l;
short s = (short) i;
byte b = (byte) s;
char c = (char) b;
System.out.println(c);
System.out.println(b);
System.out.println(s);
System.out.println(i);
System.out.println(l);
System.out.println(f);
System.out.println(d);
}
}
運行結果為:
a
97
97
97
97
97.0
97.0
=====================我是分割線========================
a
97
97
97
97
97.0
97.0
注意:
數據類型轉換必須滿足如下規則:
1. 不能對boolean類型進行類型轉換。
2. 不能把對象類型轉換成不相關類的對象。
3. 在把容量大的類型轉換為容量小的類型時必須使用強製類型轉換。
4. 轉換過程中可能導致溢出或損失精度 比如:
/**
* byte類型的最大值我127
* 當int的值為128是就會溢出
*/
public class Test {
public static void main(String[] args) {
int i = 128;
byte b = (byte) i;
System.out.println(i);
System.out.println(b);
}
}
- 浮點數到整數的轉換是通過舍棄小數得到,而不是四舍五入
class Test2{
public static void main(String[] args) {
int i = (int) 23.7;
System.out.println(i);
}
}
明天開始接接觸Java變量的申明及使用.
最後更新:2017-05-22 20:31:18