2
class Test
{  
   public static void main(String[] args) 
   { 
     byte t1 = 111;
     byte t2 =11;
     byte t3 = t1+t2;

     System.out.println(t1+t2);   

   }  
}  

In eclipse it is showing error cannot convert from int to byte.Here sum is 122 which range in the byte range.So why i am getting this error here.

Thanks in advance...

4
  • 1
    Addition results in int. you have to explicitly downcast it
    – Chris
    May 19, 2013 at 10:14
  • 122 is in the range of byte?
    – PSR
    May 19, 2013 at 10:15
  • 122 is in the range of byte. However, the result you see (122) is at int. So it needs downcasting
    – Chris
    May 19, 2013 at 10:16
  • A byte can hold 256 values. It goes from 0 to 255 for unsigned bytes and from -128 to 127 for signed bytes.
    – SJuan76
    May 19, 2013 at 10:17

2 Answers 2

5

When you do mathematical operations on byte, Java do Widening( automatic type promotion) to byte(implicitly up casted) to integer this case. so when you perform

 byte t3 = t1+t2; //  t1+t2; will be evaluated as integer.

As t1+t2 result is wider than byte so you need to downcast it to byte.

To remove compilation error.

 byte t3 = (byte) (t1+t2); // typecast to byte

For more information please read JLS 5.1.2

0
byte t3 = t1 + t2;

For the statement above, the compiler puts the actual values and tries to compute it:

byte t3 = 111 + 11;

However, these numbers are integer literals, that's why the compiler complains. You have to do explicit casting:

byte t3 = (byte) (t1 + t2);
1
  • 1
    Actually, this explanation is incorrect. t1 and t2 are NOT integer literals. They are byte variables. The real explanation is that integral operands of an arithmetical operator are promoted to (at least) int. See stackoverflow.com/questions/16633949/…
    – Stephen C
    May 19, 2013 at 11:34

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.