09-类型转换

类型转换

  • 由于java是强类型语言,所以要进行有些运算的时候,需要用到类型转换

    低--------------------------------------高

    byte,short,char-> int -> long -> float -> double

     

  • 运算中,不同类型的数据先转化为同一类型,然后进行转换

  • 强制类型转换

  • 自动类型转换

 
 1 public class Demon04 {
 2      public static void main(String[] args) {
 3          int i = 128;
 4          byte b = (byte) i;//内存溢出
 5  6          //强制转换  (类型)变量名 高--低
 7          //自动转换  低--高
 8  9          System.out.println(i);
10          System.out.println(b);
11 12          /*
13          注意点:
14          1. 不能对布尔值进行转换
15          2. 不能把对象转换为不想关的类型
16          3. 在把高容量转换到低容量的时候,强制转换
17          4. 转换的时候可能存在内存溢出, 或者精度问题
18           */
19          System.out.println("================================");
20          System.out.println((int)23.7);//23
21          System.out.println((int)-45.89f);//-45
22 23          System.out.println("================================");
24          char c = 'a';
25          int d = c+1;
26          System.out.println(d);
27          System.out.println((char) d);
28 29      }
30  }

 
 1 public class Demon05 {
 2      public static void main(String[] args) {
 3          //操作比较大的数的时候,注意溢出问题
 4          //JDK7新特性,数字之间可以用下划线分割
 5          int money = 10_0000_0000;
 6          int year = 20;
 7          int total = money*year;//-1474836480,计算的时候溢出了
 8          long total2 = money*year;//默认是int,转换之前已经存在问题了,右边先算完在左边转换的
 9 10          long total3 = money*((long)year);
11          System.out.println(total3);
12          
13          //
14      }
15  }


 


 ​

 

posted @ 2021-03-17 21:44  小carlos  阅读(56)  评论(0)    收藏  举报