1

While learning about implicit and explicit type casting, I tried the following code:

class Implicit
{
    public static void main(String args[])
    {
        byte a=10;
        byte b=20;

        a=a+b; //

        System.out.println(a);
    }
}

The compiler reports:

enter image description here

I tried this code to see if a unary operator or any other operation in such example can cause the data type on the Right Hand Side to change.

Is this what is happening here? If so, what is the reason? What other situations would cause the data type to be altered?

Richard Chambers
  • 16,643
  • 4
  • 81
  • 106
rajagrawal
  • 622
  • 4
  • 14
  • 26

3 Answers3

4

Compiler warns you because byte+byte = int Thus, it warns you when to try to add two bytes(essentially an int after the addition) and assign it to an byte, which would lead to loss of precision, as byte can only hold 8 bits where as an int can hold 32 bits.

However, this would not give you a warning when you use compound assignment operator.

    a+=b; //
PermGenError
  • 45,977
  • 8
  • 87
  • 106
1

It warns your

possible loss of precision

because the addition operator causes each of the byte values to be promoted to an int before the addition is done (Binary Numeric Promotion). So byte+byte would be an int result and to assign back to a byte a it needs to downcast int to byte. The downcast may result in loss of precision if the value of the addition is greater than can be stored as a byte value.

You can force compiler to accept this by explicitly downcast as a=(byte)(a+b) where signals that you know the risk and compiler shouldn't care.

Richard Chambers
  • 16,643
  • 4
  • 81
  • 106
harsh
  • 7,502
  • 3
  • 31
  • 32
0

the add operations cause the byte variable to be promoted to int.

see the answer to this question Add bytes with type casting, Java

i dont quite know why with java, but it seems for c#(yes, c# have similar result), it's for performance sake. See here for details byte + byte = int... why?

Community
  • 1
  • 1
bysreg
  • 793
  • 1
  • 9
  • 30