0

Can someone kindly tell me why I need the following cast in my Java class?

sum = (byte)(sum + array[i]);

If I have the cast the program compiles, but if I remove it the program won't compile.

But in this case both array and sum are declared as byte. So why can't you add two byte types to get a byte result? If I change byte to int, then it will work fine. But why?

Thanks very much.

public class FindSumOfByteArray
{
    public static void main(String[] args)
    {
        byte[] array = {-2,  9,  0,  7};

        byte sum = 0;

        for(int i = 0; i < array.length; i++)
        {
            sum = (byte)(sum + array[i]);
        }

        System.out.println("Sum = " + sum);
    }
}

The error message would say:

FindSumOfByteArray.java:18: error: incompatible types: possible lossy conversion from int to byte
            sum = sum + array[i];
                      ^
1 error
James Z
  • 12,209
  • 10
  • 24
  • 44
naswari
  • 1
  • 1

0 Answers0