Java基础部分04

基本类型转换

自动类型转换

自动类型转换:精度小的类型可以自动转换为精度达的数据类型,如下图:

注意事项:

  1. 精度小的会自动转换为精度大的数据类型。

  2. (byte,short)和char之间不会自动转换,如上图可见。

  3. boolean不参与数据类型转换。

  4. byte,short和char他们三者运算是结果会首先转换为int类型。

  5. 自动提升原则:表达式结果的类型会自动提升为操作数中最大的类型。(如下代码)

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
*/

强制类型转换

强制类型转换:将数据容量大的数据类型转换为数据容量小的数据类型,但是会造成数据溢出,精度丢失。

注意事项:

  1. 强制类型转换是数据类型大的转换成数据类型小的。

  2. 强制类型符号只针对最近的操作数有效。

  3. char类型可以保存int常量值,不能保存int变量值

  4. byte和short在运算是,当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开始,在转换时保证数据的有效性。

 

posted @ 2021-09-29 16:19  请叫我笨蛋  阅读(42)  评论(0)    收藏  举报