Byte incrementation operation in Java

advertisements

This question already has an answer here:

  • why byte += 1 compile but byte = byte + 1 not? 8 answers

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.


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);

Whereas, b++ will work fine. It (++ operator) automatically casts the value b + 1 which is an int to a byte.


This is clearly listed in JLS - ยง15.26.2 Compound Assignment Operators : -

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


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.