int i = 128;
byte b = (byte) i;
System.out.println(i);// 128
System.out.println(b);// -128 byte的范围是127~-128,超出的就-128
double d = i;
System.out.println(d);// 128.0
在java中,类型转换分为两种,强制转换和自动转换。
byte b = (byte) i;
double d = i;
注意点:
- 不能对布尔类型进行转换;
- 不能把对象类型转换成不相干的类型;
- 把高容量转换成低容量时,强制转换;
- 转换的时候可能存在内存溢出或者精度问题,需要注意;
System.out.println((int) 23.7);//23
System.out.println((int)-45.89F);//-45
char c = ‘a‘;
int s = c + 1;
System.out.println(s);//97
System.out.println((char) s);//b
//JDK1.7新特性,数字之间可以用下划线‘_‘分割
int money = 10_0000_0000;
int years = 20;
int total = money * years;
System.out.println(total);//-1474836480
long total2 = money * years;
System.out.println(total2);//-1474836480
long total3 = money *((long) years);
System.out.println(total3);////20000000000
原文:https://www.cnblogs.com/xd-study/p/12828506.html