由于Java是强类型语言,所以要进行有些运算的时候,需要进行类型转换
低<------------------------------------------------->高
byte,short,char --> int --> long --> float --> double
(低 --> 高 代表着他们的容量 float和double比int和long高是因为小数的优先级大于整数)
运算中,不同类型的数据要进行类型转换,转化为同一类型,然后进行运算
运算实例
public class transformation {
public static void main(String[] args) {
int i = 128;
byte b = (byte)i;
System.out.println("i===" + i);
System.out.println("b===" + b);
System.out.println("==============================================================");
int a = 128;
double c = i;
System.out.println("a===" + a);
System.out.println("c===" + c);
System.out.println("==============================================================");
System.out.println((int)23.7);
System.out.println((int)47.76f);
System.out.println("===============================================================");
char f = 'a';
int d = f+1;
System.out.println(f);
System.out.println(d);
System.out.println((char)d);
}
}
操作比较大的数时,要注意溢出问题
int money = 10_0000_0000;
int years = 20;
System.out.println("money =" + money);
int total = money*years;
System.out.println("total =" + total);
long total1 = money*years;
System.out.println("total1 =" + total1);
long total2 = money*((long)years);
System.out.println("total2 =" + total2);