b)? 20:30; Error: incompatible types: possible lossy -6ren">
gpt4 book ai didi

java - 不一致的 "possible lossy conversion from int to byte"编译时错误

转载 作者:IT老高 更新时间:2023-10-28 21:06:20 27 4
gpt4 key购买 nike

检查以下代码片段:

片段 #1

int a=20;
int b=30;
byte c= (a>b)? 20:30;
Error:
incompatible types: possible lossy conversion from int to byte
byte c= (a>b)? 20:30;

片段 #2

int a=20;
int b=30;
byte h1=70;
byte c= (a>b)? 20:h1;

片段#3

int a=20;
int b=30;
byte h1=70;
byte h2=89;
byte c= (a>b)? h1:h2;

片段 #4

byte c= (true)? 20:30;

除了 Snippet #1 之外,所有这些都可以正常编译。这种行为如何合理?如果 Snippet #1 产生“可能的有损转换”错误,Snippet #2 和 4 也应该,因为它们仍然包含 int 类型的文字。为什么编译成功?

最佳答案

J.L.S 15.25.解释了这种行为。

片段 #1:

If the second and third operands have the same type (which may be the null type), then that is the type of the conditional expression

第二个和第三个操作数都是int字面量,所以表达式的类型也是int,不能赋值给一个byte 没有显式转换的变量。因此编译错误。

片段 #2:

If one of the operands is of type T where T is byte, short, or char, and the other operand is a constant expression (§15.28) of type int whose value is representable in type T, then the type of the conditional expression is T.

一个操作数是一个byte,另一个是一个int字面量,其值可以表示为byte,所以表达式的类型是byte,可以赋值给一个byte变量。

片段 #3:

If the second and third operands have the same type (which may be the null type), then that is the type of the conditional expression

第二个和第三个操作数都是byte,所以表达式的类型是byte,可以赋值给一个byte变量.

片段 #4:

由于3个操作数都是常量,整个三元表达式就是一个常量表达式,所以编译器把这个表达式当作一个简单的赋值——byte c = 20;——这是有效的。

关于java - 不一致的 "possible lossy conversion from int to byte"编译时错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56162939/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com