由于 Java 是强类型语言,所以要进行有些运算的时候,需要用到类型转换
运算中,不同类型的数据先转换为同一类型,然后进行运算
public class HelloWorld {
public static void main(String[] args) {
//强制转换
int a = 128;
byte b = (byte)a; //将 a 强制转换成 byte 类型
/*
Byte 类的 MAX_VALUE = 127
赋值 128 会出现内存溢出问题
*/
System.out.println(a);
System.out.println(b);
System.out.println("--------------------");
//精度问题
System.out.println((int)3.1415);
System.out.println((int)-3.1415f);
}
}
输出结果为:
128
-128
--------------------
3
-3
public class HelloWorld {
public static void main(String[] args) {
//自动转换
int c = 128;
double d = c; //将 c 自动转换成 double 类型
System.out.println(c);
System.out.println(d);
System.out.println("--------------------");
char e = ‘a‘;
int f = e + 1;
System.out.println(f);
System.out.println((char)f);
}
}
输出结果为:
128
128.0
--------------------
98
b
public class commonProblem {
public static void main(String[] args) {
//操作较大的数注意溢出问题
int myAnnualIncome = 1_000_000_000; //数字之间可以用下划线分割,且不被输出
int myAge = 17;
int total1 = myAnnualIncome * myAge;
long total2 =myAnnualIncome * myAge;
long total3 =((long)myAnnualIncome) * myAge; //先把一个数转换为 long类型
System.out.println(total1); //-179869184,溢出了
System.out.println(total2); //-179869184,默认是 int 类型,转换之前已经存在问题了
System.out.println(total3); //17000000000,没有溢出
}
}
输出结果为:
-179869184
-179869184
17000000000
原文:https://www.cnblogs.com/puyulin/p/14381015.html