类型转换

`public class Demo02 {
public static void main(String[] args) {
// 类型转换
//Java 时强类型语言 在运算时,需要进行类型转换
// 低 -----------------------------------------> 高
//byte,short,char ——> int ——>long ——>float ——> double
//
运行中,不同类型的数据先转为同一数据类型,然后进行运算。
//强制类型转换 高——>低
//
自动类型转换 低——>高
//Byte 看其定义 Ctrl+B
int i = 128;
byte b = (byte)i; //内存溢出 byte 范围 -128~127
// 强制转换

    System.out.println(i);  //128
    System.out.println(b);  //-128

    double d = i;
    System.out.println(d);
      // 由低到高时 自动转换

    /*
     注意点:
     1.不能对布尔值进行转换 (布尔值只有false,true)
     2.不能把对象类型转换为不相干的类型
     3.在把高容量转为低容量的时候,需要强制转换
     4.转换的时候可能存在溢出,或者精度问题
   */
    //操作比较大的数的时候,注意溢出问题
    //JDK7新特性,数字之间可以用下划线分割
    int money = 10_0000_0000;  //输出时下划线不会被输出
    int year = 20;
    int total = money * year;
    System.out.println(total);  // -1474836480  计算时溢出

    long total2 = money * year;   //默认是 int,转换前已经存在问题了
    System.out.println(total2);  // -1474836480

    long total3 = money * ((long)year);  //先把一个数转换为long
    System.out.println(total3);   //20000000000
}

}
`

posted @ 2022-06-11 22:00  Dalier-!  阅读(10)  评论(0)    收藏  举报