目录
隐含的强制类型转换
类型转换规则:
自动类型转换
数据类型
数据类型 | 所占字节数 | 最小值 | 最大值 | 默认值 |
byte | 1个字节(8位) | -128 | 127 | 0 |
short | 2个字节(16位) | -32768 | 32767 | 0 |
int | 4个字节(32位) | -2,147,483,648(-2^31) | 2,147,483,647(2^31 - 1) | 0 |
long | 8个字节(64位) | -2^63 | 2^63 -1 | 0L |
float | 4个字节(32位) |
1.4E-45 |
3.4028235E38 |
0.0f |
double | 8个字节(64位) |
4.9E-324 |
1.7976931348623157E308 |
0.0d |
char | 2个字节(16位) | 0 |
65535 |
‘u0000’ |
boolean | 1个字节(8位) | false | true | false |
隐含的强制类型转换
整数字面量默认位 int 型,小数字面量默认为 double 型。
类型转换规则:
- 1. 不能对boolean类型进行类型转换。
- 2. 不能把对象类型转换成不相关类的对象。
- 3. 在把容量大的类型转换为容量小的类型时必须使用强制类型转换。
- 4. 转换过程中可能导致溢出或损失精度,例如:
int i =128;
byte b = (byte)i;
- 因为 byte 类型是 8 位,最大值为127,所以当 int 强制转换为 byte 类型时,值 128 时候就会导致溢出。
自动类型转换
(1)整型、实型(常量)、字符型数据可以混合运算。运算中,不同类型的数据先转化为同一类型,然后进行运算。
(2)转换从低级到高级。
低 ------------------------------------> 高
byte,short,char—> int —> long—> float —> double
(3)byte,short,char之间进行运算时,都会先转化为int在进行计算。
(4)计算机可以自动将低类型转换为高类型,但是不能将高类型转换为低类型。
(5)当整数字面值没有超过byte,short,char,int范围时,可以直接赋值给byte,short,char,int。
(6) 当整数字面值没有超过int范围时,可以直接赋值给long,如果超过了int范围,但是没有超过long范围,可以在整数字面值后面加上L或l。
(7)小数字面值赋值给float时需要在小数末尾加上F或f。
例:
1. class A 2. { 3. public static void main(String[] a) 4. { 5. long b = 2147483648; 6. System.out.println(b); 7. //错误 8. //2147483648超出了int型 9. //应该在2147483648后面加上L 10. byte c = 10; 11. System.out.println(c); 12. //正确 13. byte d = c / 2; 14. System.out.println(d); 15. //错误 16. //c/2做运算时,会被当做int处理,高类型不能赋值给低类型 17. long e = c / 2; 18. System.out.println(d); 19. //正确 20. //c/2做运算,被当做int处理,低类型可以赋值给高类型,存在类型转换 21. float f = 3.2; 22. System.out.println(f); 23. //错误 24. //应该在3.2后面加上F或者f 25. byte g = 2; 26. byte h = 2; 27. byte i = g + h; 28. System.out.println(i); 29. //错误 30. //g和h都是byte类型,进行运算时都会先转化为int类型,结果也为int类型,int类型不能赋值给byte类型 31. double j = 10 / 3; 32. System.out.println(j); 33. //正确,编译结果为3.0 34. //10和3都是int类型,运算结果还是int类型,int类型可以转化为double类型,存在类型转换 35. j = 10.0 / 3; 36. System.out.println(j); 37. //正确,编译结果为3.3333333333333335 38. //10.0是double类型,3是整型,运算结果也是double类型 39. byte k = 4; 40. k = k + 4; 41. System.out.println(k); 42. //错误 43. //k + 4的类型为int型,int类型无法转化成byte类型 44. k+ = 4; 45. System.out.println(k); 46. //正确,编译结果为8 47. //k+ = 4 ====> k = (byte)(k + 4); 48. } 49. 50. }
发表评论