Java笔记第五课:类型转换


类型转换

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

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

byte、short、char < in t< long < float < double

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


强制类型转换

高-----底 需要强制转换

public class dada {
   public static void main(String[] args) {
       int a = 128;
       byte b= (byte)a;//内存溢出 byte max=127
       //强制转换 (类型)变量名
       System.out.println(a);
       System.out.println(b);
  }
}
Connected to the target VM, address: '127.0.0.1:62255', transport: 'socket'
128
-128
Disconnected from the target VM, address: '127.0.0.1:62255', transport: 'socket'
?
Process finished with exit code 0
?

自动类型转换

低--高 不用强制转换

public class dada {
   public static void main(String[] args) {
       int a = 128;
       double b= a;
       System.out.println(a);
       System.out.println(b);
  }
}
Connected to the target VM, address: '127.0.0.1:62283', transport: 'socket'
Disconnected from the target VM, address: '127.0.0.1:62283', transport: 'socket'
128
128.0
?
Process finished with exit code 0
?

注意点:

  1. 不能对布尔值进行转换。

  2. 不能把对象类型转换为不相干的类型。

  3. 在把低容量转换为高容量的时候,强制转换。

  4. 转换的时候可能存在内存溢出,或者精度问题!

精度问题

public class dada {
   public static void main(String[] args) {
       System.out.println((long)23.55);
       System.out.println((long)12.541264f);
       
       char c = 'a';
       int b = c+1;
       System.out.println(b);
       System.out.println((char)b);
  }
}
Connected to the target VM, address: '127.0.0.1:62338', transport: 'socket'
Disconnected from the target VM, address: '127.0.0.1:62338', transport: 'socket'
23
12
98
b
?
Process finished with exit code

溢出问题

public class dada {
   public static void main(String[] args) {
       int money = 10_0000_0000;//数字太大可以加下划线,不会被输出。
       int year = 18;
       int henyouqian =money*year;//输出820130816,计算的时候溢出了
       System.out.println(henyouqian);//默认是int,转换之前已经出问题了
?
       long jindaoweihenyouqian =money*((long)year);//18000000000,输出成功,先把一个数转为long
       System.out.println(jindaoweihenyouqian);
  }
}
?