-2

I am new to Java. So I am unable to understand the reason why this exception is occurring. Here is my code:

class St
{
    public static void main(String s[])
    {
        byte b1,b2,b3;
        b1=10;
        b2=5;
        b3=b1+b2;
        System.out.println(b3);
    }
}

Please explain.

Ryan
  • 712
  • 7
  • 21
The Game
  • 62
  • 6

8 Answers8

2

Java does not have an addition operator for bytes, so to compute b1+b2 the values are converted to int and the sum is calculated as with ints. You get the error because there is no implicit conversion from int to byte because of possible loss of precision.

You have to use an implicit casting conversion to get the sum as byte:

b3=(byte)(b1+b2);

By the way, this is not an "exception" but a compile-time error. Exceptions are produced when you run a program.

Joni
  • 108,737
  • 14
  • 143
  • 193
1

You need to Cast the result to byte because the binary operation in java should at least returns int value, So byte+byte is an int value, cast the result of two operands b1 and b2 to byte and assign it to b3 which is byte:

b3=(byte)(b1+b2);
Husam
  • 2,069
  • 3
  • 19
  • 29
1

b1 + b2 is automatically casted to int (the immediately greater primitive), because you could reach the maximum byte value, so you can't assign it to a byte without manually casting (which may result in undesired results). Try this instead.-

byte b1,b2;
int b3;
b1 = 10;
b2 = 5;
b3 = b1 + b2;
ssantos
  • 16,001
  • 7
  • 50
  • 70
1

The result of adding two bytes is an int. So, there's a potential precision loss here when you assign the int to a byte. That's what the compiler is warning you about. Hence, you need a cast () here to do it explicitly as

b3 = (byte) (b1+b2);
Ravi K Thapliyal
  • 51,095
  • 9
  • 76
  • 89
1

When you add to byte values the result would be integer so if you are trying to add to bytes and assign it to byte the it gives you the castexception.So just type cast the value of the addtion to byte or take the result type as an integer.

pnathan
  • 713
  • 3
  • 9
0

add cast to byte like this way (byte)

complete answer

class St
{
    public static void main(String s[])
    {
        byte b1,b2,b3;
        b1=10;
        b2=5;
        b3=(byte) (b1+b2);
        System.out.println(b3);
    }
}
SpringLearner
  • 13,738
  • 20
  • 78
  • 116
0

It will work after casting with byte.

b3=(byte) (b1+b2);

As + convers automatically into int.

It throws error like Type mismatch:cannot convert from int to byte.

NFE
  • 1,147
  • 1
  • 9
  • 22
0

Pretty Straight forward, try this code:

public class st
{
    public static void main(String s[])
    {
        byte b1,b2,b3;
        b1=10;
        b2=5;
        b3=(byte) (b1+b2);
        System.out.println(b3);
    }
}
Manish Tuteja
  • 205
  • 1
  • 7