自动类型转换
-
范围小的变量,可以直接赋值给类型大的变量。
public class emo{ public static void main (String [] args ){ short a = 8; int b; b = a; System.out.println(b); } }
表达式的自动类型转换
在表达式中小范围的变量会自动转换成当前大范围的变量类型再运算。
public class emo{
public static void main (String [] args ){
char n = 7;
short m = 6;
char b = n + m;
System.out.println(b);
}
}
这种写法是错误的,char 以及 short 在运算时会自动转换成 int 类型。
强制类型转换
public class emo {
public static void main ( String [] args ){
int a = 20 ;
byte b = (byte)a;
System.out.println(b);
}
}
public class emo {
public static void main ( String [] args ){
int a = 20 ;
byte b = (byte)a;
System.out.println(b);
}
}
public class emo {
public static void main ( String [] args ){
int a = 20 ;
byte b; b = (byte)a;
System.out.println(b);
}
}
强制类型转换转换类型需要带()
转换的对象如果是算式时也需要带括号。
(int)a + b;
只会对 a 进行转换。
想要转换 a + b 。
需要将格式写为
(int)(a + b);
这点和C语言相同。
强制转换的注意事项
强制类型的转换会造成数据的丢失(溢出)。
浮点型转换为整形是直接丢掉小数部分,仅保留整数部分返回。