-5
class Example{
    public static void main(String args[]){
        byte b1=10,b2=20,b3;    
        b3=b1+b2;
        System.out.println(b3);
    }   
}
khelwood
  • 55,782
  • 14
  • 81
  • 108
  • 1
    If only compile errors included some kind of information about what the problem was. – khelwood Feb 26 '19 at 08:51
  • The java compiler usually aids you why it is unable to compile. Try to read the message(s) it is displaying so that you can figure out the problem quickly. That is a good skill for in the future when facing compilation problems of a big project. – KarelG Feb 26 '19 at 08:51
  • It showed this. possible lossy conversion from int to byte – Shehani Munasinghe Feb 26 '19 at 08:56
  • Here https://stackoverflow.com/questions/28623477/lossy-conversion-from-int-to-byte – Suraj Rao Feb 26 '19 at 09:25

1 Answers1

1

Adding two bytes produces an int. You cannot assign an int to a byte without casting it.

You need to do this:

byte b1 = 10, b2 = 20, b3;
b3 = (byte) (b1 + b2);
System.out.println(b3);

Or this:

byte b1 = 10, b2 = 20;
int b3 = b1 + b2;
System.out.println(b3);
ᴇʟᴇvᴀтᴇ
  • 12,285
  • 4
  • 43
  • 66