java語言中的型別轉換
1、自動型別轉換
要注意的點:
(1)兩種型別要相互相容
(2)高型別不能轉成低型別,低型別可以轉成高型別
(3)如果非要高型別轉低型別,就必須要用到下面 下麪的強制型別轉換
public class text{
public static void main(String[] args){
short s = 123;
int i = s;
System.out.println(i);
float f = 100.0F;
double d = f;
System.out.println(d);
int i2 = 100;
double d2 = i2;
System.out.println(d2);
char c = 'A';
int i3 = c;
System.out.println(i3);
char c2 = 'a';
double d3 = c2;
System.out.println(d3);
boolean bool = true;
int i4 = bool;
}
}
2、強制型別轉換
public class text{
public static void main(String[] args){
short s = 123;
byte b = s;
System.out.println(b);
}
}
強制型別轉換:(目標型別)值
public class text{
public static void main(String[] args){
short s = 123;
byte b = (byte)s;
System.out.println(b);
}
}
如果被轉換的值在要轉換的值的範圍內,數據是會完整儲存的;
如果被轉換的值不在要轉換的值的範圍內,數據是會被截斷的。
public class text{
public static void main(String[] args){
short s = 123;
byte b = (byte)s;
System.out.println(b);
short s2 = 257;
byte b2 = (byte)s2;
System.out.println(b2);
}
}