在 Java 程序中,不同的基本数据类型的数据之间经常需要进行相互转换。例如:

代码中 int型变量 score1 可以直接为 double 型变量 score2 完成赋值操作,运行结果为:82.0
这种转换称为自动类型转换。
当然自动类型转换是需要满足特定的条件的:
1. 目标类型能与源类型兼容,如 double 型兼容 int 型,但是 char 型不能兼容 int 型

2. 目标类型大于源类型,如 double 类型长度为 8 字节, int 类型为 4 字节,因此 double 类型的变量里直接可以存放 int 类型的数据,但反过来就不可以了

网友评论