Fork me on GitHub

六.类型转换

自动类型转换

自动类型转换指的是容量小的数据类型可以自动转换为容量大的数据类型。如图所示,黑色的实线表示无数据丢失的自动类型转换,而虚线表示在转换时可能会有精度的损失。

image

至于为什么double类型比long类型表示的范围大请移步double和long类型:

自动类型转换

可以将整型常量直接赋值给byte、 short、 char等类型变量,而不需要进行强制类型转换,只要不超出其表数范围即可。

1
2
short  b = 12;  //合法
short b = 1234567;//非法,1234567超出了short的表数范围

image

强制类型转换

强制类型转换,又被称为造型,用于显式的转换一个数值的类型。在有可能丢失信息的情况下进行的转换是通过造型来完成的,但可能造成精度降低或溢出。

语法格式:

1
(type)var

运算符“()”中的type表示将值var想要转换成的目标数据类型。

强制类型转换

1
2
3
4
5
6
7
double x  = 3.14; 
int nx = (int)x; //值为3
char c = 'a';
int d = c+1;
System.out.println(nx);
System.out.println(d);
System.out.println((char)d);

image

基本类型转化时常见错误和问题

操作比较大的数时,要留意是否溢出,尤其是整数操作时。

常见问题一

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
/**
* @author RickYinPeng
* @ClassName Y_13_基本类型转换时常见错误
* @Description
* @date 2018/11/2/21:50
*/
public class Y_13_基本类型转换时常见错误 {
public static void main(String[] args) {
int money = 1000000000; //10亿
int years = 20;
//返回的total是负数,超过了int的范围
int total = money*years;
System.out.println("total="+total);

//返回的total仍然是负数。默认是int,因此结果会转成int值,再转成long。但是已经发生//了数据丢失
long total1 = money*years;
System.out.println("total1="+total1);

//返回的total2正确:先将一个因子变成long,整个表达式发生提升。全部用long来计算。
long total2 = money*((long)years);
System.out.println("total2="+total2);

/* int l = 2; //分不清是L还是1,
long a = 23451l;//建议使用大写L
System.out.println(l+1);*/
}
}

image