数据类型的转换
低------------------------------------------------>高
byte,short,char->int->long->float->double
运算中,不同类型的数据先转化为同一类型,然后进行运算
public class Demo03 {
public static void main(String[] args) {
int i = 128;
byte b = (byte)i;//内存溢出 输出结果为-128
float a = i;
//强制转换 (类型)变量名 高--低
//自动转换 低--高
System.out.println(i);
System.out.println(b);
System.out.println(a);
/*注意点:不能对布尔值进行转换
不能把对象类型转化为不相干类型
在把高容量转化为低容量时,强制转换
转换时候可能有内存溢出,或者精度问题
*/
System.out.println("==============");
System.out.println((int)23.7);//23
System.out.println((int)-45.89f);//-45
System.out.println("==============");
char c = 'a';
int d = c+1;
System.out.println(d);
System.out.println((char) d);
}
}
简单实例
public class Demo04 {
public static void main(String[] args) {
//操作比较大的数的时候,注意溢出问题
//JDK7新特性,数字之间可以用下划线分割
int money = 10_0000_0000;
int years = 20;
int total = money*years;//-1474836480,计算的时候溢出
long total2 = money*years;//默认是int,转换前就已经存在问题
//第一种解决方法
long total3 = money*((long)years);
//第二种解决方法
long total4 = ((long)money)*years;
//第三种解决方法
long money2 = 10_0000_0000L;
long years2 = 20L;
long total5 = money2*years2;
System.out.println(total);
System.out.println(total2);
System.out.println(total3);
System.out.println(total4);
System.out.println(total5);
}
}
浙公网安备 33010602011771号