对常量求和时的隐式缩小与对变量求和时的显式缩小 [英] Implicit narrowing when summing constants vs explicit narrowing when summing variables
本文介绍了对常量求和时的隐式缩小与对变量求和时的显式缩小的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我已经写了一个程序.
class First
{
public static void main(String[] args)
{
int c = 5;
byte b = c+6;
System.out.println(b);
}
}
我的javac输出是:
And my javac output is:
error: incompatible types: possible lossy conversion from int to byte
byte b = c+6;
^
1 error
但是如果我将该程序修改为:
But if I modify the program as:
class First
{
public static void main(String[] args)
{
byte b = 5+6;
System.out.println(b);
}
}
执行正常,输出:
11
我知道在操作之前,两个操作数都将转换为整数.然后,+运算符将得出一个整数.但是,如果变量c是整数,则默认情况下常数5也是整数.为什么在第二种情况下javac不会导致错误?
I know that before operation, both operands gets converted in integer. Then the + operator results in an integer. But if the variable c was an integer, then the constant 5 is also an integer by default. Why does not javac results an error in the second case?
如果我在概念上错了,请指导我.
Please guide me if I am conceptually wrong.
推荐答案
查看全文