繁花似锦觅安宁

导航

Java类型转换

int i = 128;
byte b = i;//报错
byte b = (byte)i;//-128 强制转换,内存溢出

低---------------------------------------------------------->高

byte,short,char-> int -> long -> float -> double

基本类型之间比较时低精度自动转化成高精度

byte 1个字节

short 2个字节

char 2个字节

byte,char,short都不会存在隐式转换,相互之间只能进行强制类型转换

他们三者在计算时首先转换为int类型

int 4个字节

float 4个字节

long 8个字节

double 8个字节

强制转换:高-->低

自动转换:低-->高

  1. 不能对布尔值进行转换

  2. 不能把对象类型转换为不相干类型

  3. 在把高容量转换为低容量时,强制转换

  4. 转换时可能存在内存溢出或精度问题

     

//精度问题
System.out.print((int)23.7);//23
System.out.print((int)-45.78f);//-45
char c = 'a';//a
int d = c+1;//98
System.out.print((char)d);//b

操作比较大的数的时候,主意内存溢出问题

//JDK7新特性,数字之间可以用_分割
int money = 10_0000_0000;//1000000000
int year = 20;
int total = money*year;//-1474836480,计算的时候溢出了
long total2 = money*year;//也是个负数,默认是int,转换之前已经存在问题了
//先把一个数转换为long
long total3 = money*((long)years);//20000000000

//L 和 l,一般由于L更好区分,所以尽量使用L

posted on 2020-03-13 12:26  繁花似锦觅安宁  阅读(121)  评论(0编辑  收藏  举报