在Java中用字节递增操作
当我们尝试使用递增运算符和加法运算符递增字节变量时会发生什么。
What happens when we try to increment a byte variable using increment operator and also by addition operator.
public class A{
public static void main(String args[])
{
byte b=1;
b++;
b=b+1;
}
}
请给我在哪里我们可以找到释放出这么小的东西?请帮帮我。
Please give me the source where we can find such small things unleashed ? Please help me out.
差异就是,
,从 ++
运算符中的隐式转换 int
到 byte
,然而,如果您使用 b = b + 1 $ c,则必须明确
$ c>
The difference is that, there is an implicit casting
in the ++
operator from int
to byte
, whereas, you would have to do that explicitly
in case you use b = b + 1
b = b + 1; // will not compile. Cannot cast from int to byte
您需要一个明确的演员: -
You need an explicit cast: -
b = (byte) (b + 1);
然而, b ++
将正常工作。它( ++
运算符)自动转换值 b + 1
这是一个 int
到字节
。
Whereas, b++
will work fine. It (++
operator) automatically casts the value b + 1
which is an int
to a byte
.
这清楚地列在 JLS - §15.26.2复合赋值运算符: -
This is clearly listed in JLS - §15.26.2 Compound Assignment Operators : -
E1 op = E2形式的复合赋值表达式相当于
到E1 =(T)((E1)op(E2)),其中T是E1的类型,除了E1
被评估只有一次
A compound assignment expression of the form E1 op= E2 is equivalent to E1 = (T) ((E1) op (E2)), where T is the type of E1, except that E1 is evaluated only once
注意操作 b + 1
将为您提供类型 int
的结果。所以,这就是你在第二次任务中需要明确演员的原因。
Note that operation b + 1
will give you a result of type int
. So, that's why you need an explicit cast in your second assignment.