我知道'==‘操作符检查它们是否存在于char中相同的内存位置,但是为什么,当我比较char和double数据类型时,Java给了我true?它们不是不同的数据类型吗?以及为什么它没有给我编译时错误,因为根据文档:
如果我们将==应用于对象类型,那么参数类型之间应该有兼容性(子到父、父到子或者相同类型)。否则,我们将得到编译时错误。
发布于 2022-05-22 08:22:01
发布于 2022-05-22 08:23:44
在Java中,char和double是原语,它们通过使用==进行值比较,而不是按内存位置进行比较,这仅适用于对象(引用类型)。
当您执行'a' == 97.0时,这是char和double之间的比较。char是一个无符号整数,与double相比,char经历了向double的扩展转换。字符'a'对应于数字值97,因此当转换为double时,它是97.0。给定97.0 == 97.0是真的,这是表达式的结果。
还请参阅Java语言规范中的内容:
1. [..]2. Next, widening primitive conversion ([§5.1.2](https://docs.oracle.com/javase/specs/jls/se17/html/jls-5.html#jls-5.1.2)) and narrowing primitive conversion ([§5.1.3](https://docs.oracle.com/javase/specs/jls/se17/html/jls-5.html#jls-5.1.3)) are applied to some expressions, according to the following rules: - If any expression is of type double, then the promoted type is double, and other expressions that are not of type double undergo widening primitive conversion to double.https://stackoverflow.com/questions/72335832
复制相似问题