Byte increment operation in Java

What happens when we try to increment a byte variable using the increment operator as well as the addition operator.

public class A { public static void main(final String args[]) { byte b = 1; b++; b = b + 1; } } 

Please give me a source, where can we find such small things unleashed? Please help me.

+4
java
source share
4 answers

The difference is that in the ++ operator there is implicit casting from int to byte , whereas you have to do it 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. The ++ operator automatically casts the value b + 1 , which is an int byte .


This is clearly indicated in JLS - ยง15.26.2 Complex assignment operators :

A compound assignment expression in the form E1 op = E2 is equivalent to E1 = (T) ((E1) op (E2)), where T is a type of E1, except that E1 is evaluated only once


Note that the operation b + 1 will give you an int type result. That is why you need an explicit cast in the second assignment.

+11
source share

What's happening? Actually b = b + 1 will not compile.

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

b = (byte)(b + 1);

+3
source share

This variable will be doubled.

0
source share

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

b will be 3 until the main method completes.

Edit: in fact they are not equivalent: b = b + 1; incorrect and should be b = (bytes) (b + 1); [discarded in bytes, otherwise it is int]

0
source share

All Articles