在Java中用字节递增操作 [英] Byte incrementing operation in Java

查看:173
本文介绍了在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>

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.

这篇关于在Java中用字节递增操作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆