Java基础部分04
基本类型转换
自动类型转换
自动类型转换:精度小的类型可以自动转换为精度达的数据类型,如下图:

注意事项:
-
精度小的会自动转换为精度大的数据类型。
-
(byte,short)和char之间不会自动转换,如上图可见。
-
boolean不参与数据类型转换。
-
-
自动提升原则:表达式结果的类型会自动提升为操作数中最大的类型。(如下代码)
short s = 1; byte b = 1; short total = s + b; System.out.println(total);
/* 所报错误为:int类型 转换 short类型会有损失 Compilation Failed /usercode/file.java:8: error: incompatible types: possible lossy conversion from int to short short total = s + b; ^ 1 error */
强制类型转换
强制类型转换:将数据容量大的数据类型转换为数据容量小的数据类型,但是会造成数据溢出,精度丢失。
注意事项:
-
-
强制类型符号只针对最近的操作数有效。
-
char类型可以保存int常量值,不能保存int变量值。
-
基本数据类型和String类型转换
基本数据类型 =======》 String string = 基本数据类型 + " ";
String =======》 byte Byte.parseByte(String string);
String =======》 short Short.parseShort(String string);
String =======》 int Integer.parseInt(String string);
String =======》 long Long.parseLong(String string);
String =======》 float Float.parseInt(String string);
String =======》 double Double.parseDouble(String string);
String =======》 char String.charAt(int index);
注意:index从0开始,在转换时保证数据的有效性。

浙公网安备 33010602011771号