轉型,cast,promption
CAST(轉型)
- 自動轉型限於數值間的轉換(包含char),不包含boolean、String
- 整數時資料型態預設為int,浮點數時預設為double,轉型時視右邊是否能轉型為左邊(範圍要符合)
- 浮點數不會自動轉為整數,整數會自動轉換為浮點數
public static void main(String[] args) throws IOException {
// 1.
// int a = true; //cannot convert from boolean to int
// 2.
byte b = 123;
// byte c = 128; //cannot convert from int to byte
long d = 123456;
// long e = 2147483648;//int is out of range
long f = 2147483648L;
double g = 3.14f;
// 3.
double h = 1234;//1234.0
// int i =12.0;//cannot convert from double to int
}
Promotion
- 運算時以最長的長度為主,其它數值自動提昇
public static void main(String[] args) {
int a = 3;
double b =a*3.14159;
short c =2;
short d =3;
// short e = c+d; //cannot convert from int to short(可以想為雖然cast狀態可以過,但兩個數值相加後不保證可轉型)
short e = (short)(c+d);
short f = 4;
long g =5;
// int h = f+g;//cannot convert from long to int
int h = (int)(f+g);
}
openhome.cc的問題
public static void main(String[] args) {
System.out.println(Integer.MIN_VALUE == -Integer.MIN_VALUE);
}
原因為溢位,可以參考stack overflow這一篇,2補數可參考這個部落格
Reference: