转换数据类型
public class Demo06 {
public static void main(String[] args) {
int i = 128;
double b = i;
//强制转换: (类型)变量名 高——底
//自动转换: 底——高
System.out.println(i);
System.out.println(b);
/*
1、不能对布尔值进行转换;
2、不能把对象类型转换为不相干类型;
3、强制转换发生在高容量类型到底容量类型;
4、转换时注意内存溢出、精度。
*/
System.out.println("==============================");
System.out.println((int)23.7);//23
System.out.println((int)-45.89);//-45
System.out.println("==============================");
char c = 'a';
int d = c+1;
System.out.println(d);
System.out.println((char)d);
System.out.println(c);
}
}
输出:
128
128.0
==============================
23
-45
==============================
98
b
a
Process finished with exit code 0
public class Demo06{
public static void main(String[] args) {
//溢出
//数字之间用下划线分隔
int money = 10_0000_0000;
int years = 20;
int total = money*years;//溢出
long total2 = money*years;//溢出,默认int,转换之前已经计算出了。
long total3 = money*((long)years);
System.out.println(total);
System.out.println(total2);
System.out.println(total3);
}
}
输出:
-1474836480
-1474836480
20000000000
Process finished with exit code 0
浙公网安备 33010602011771号