-
由于Java是强类型语言,所以在有些运算中会用到类型转换
-
容量排序
低 ----------------------------------------------------------------------->高
byte,short,char --> int —> long ----> float —> double
public class Demo6 {
public static void main(String[] args) {
int num1 = 128;
/*
* 1. (类型)变量名 强制类型转换 高 ---> 低
* 2. 自动转换 低 ---> 高
* */
byte num2 = (byte) num1; // 内存溢出
System.out.println(num1); // 128
System.out.println(num2); // -128
/*
* 注意点:
* 1.不能对布尔类型进行转换
* 2.不能把对象类型转换成不相干的类型进; 例:人 ---> 猪 很明显是错误的!
* 3.在高容量转换成低容量时,要强制转换
* 4.强制转换可能存在内存溢出问题,或者精度问题
* */
System.out.println("===============");
System.out.println((int)23.75); // 23
System.out.println((int)-49.58f); // -49
System.out.println("===============");
char char1 = 'a';
System.out.println(char1+1); // 98
System.out.println((char)(char1+1)); // b
}
}
输出结果:
操作较大数时内存溢出的问题
public class Demo7 {
public static void main(String[] args) {
// 操作较大数的时候,注意内存溢出问题
// JDK7新特性 ,数字之间可以用下划线分隔,这些下划线并不会被输出。
int money = 10_0000_0000;
System.out.println(money);
int years = 20;
int total = money * years; //-1474836480 计算的时候溢出了
System.out.println(total);
long total2 = money * years;
System.out.println(total2); //-1474836480 计算的时候已经溢出了
long total3 = money * (long) years;
System.out.println(total3); //20000000000
}
}
输出结果: