1

Here are codes,the last second row couldn't compile out cause of the result is int?So,can I solve that every non integer type in java process as integer in arithmetic? And I am learning English from all guys,thank you.

  byte a=0;
    for(int i=0;i<128;i++){
        a=(byte)i;
     }
     byte b=1;
     byte c=0;
     c=b+a;
     System.out.println(b);
wyh
  • 43
  • 1
  • 5

2 Answers2

1

Addition operation in java between two shorts or bytes happens after converting both the operands to int and results in an int. So you need to cast your result to byte as it is a lossy conversion. See this

  • Suddenly I got java designed that for byte is too narrow to fill the data,If my turn to do it maybe I would consider it too – wyh Jan 20 '18 at 14:35
0

You have to cast a or the result of the addition of a and b to a byte, since a is an integer and it's value might not fit into a byte.
Example:

c = (byte) ((byte) a + b);

or

c = (byte) (a + b);

This way, b gets implicitly converted to an integer, the result is then casted to a byte again.

Martin Fink
  • 1,746
  • 3
  • 16
  • 32