6

What happens when we try to increment a byte variable using the increment operator and also by the addition operator.

public class A {
    public static void main(final 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.

Sae1962
  • 1,122
  • 15
  • 31
Praveen
  • 121
  • 1
  • 2
  • 8

4 Answers4

13

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 if 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. The ++ 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


Please 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.

TechDog
  • 3,039
  • 1
  • 24
  • 30
Rohit Jain
  • 209,639
  • 45
  • 409
  • 525
3

What happens? Actually b = b + 1 won't compile.

You must explicitly convert it to byte, because b + 1 evaluates to int. And it is not guaranteed that an int can fit into a byte.

b = (byte)(b + 1);

Petar Minchev
  • 46,889
  • 11
  • 103
  • 119
0

The variable will be incremented twice

Blank Chisui
  • 1,043
  • 10
  • 25
0

b++; and b=b+1; are equivalent and will result in the same bytecode.

b will be equal to 3 before the main method is finished.

Edit: actually they are not equivalent: b=b+1; is wrong and should be b=(byte) (b+1); [cast to a byte, otherwise it is an int]

Burkhard
  • 14,596
  • 22
  • 87
  • 108