1

I'm wondering why the //1 statements are accepted by the compiler and the //2 statements are not

    //1
    int k = 99999999;
    byte l = (byte)k;

    //2
    byte b = 1;
    int i = 10;
    byte z = (byte)i+b; //compiler rejected 

Type mismatch: cannot convert from int to byte using ternary operator gave me somewhat of an idea but I don't understand why the compiler can resolve the variable l in //1 as acceptable and not i in //2

Ben
  • 309
  • 1
  • 14
  • 2
    Operator/casting precedence. If you write `(byte)(i+b)` it will work. Otherwise the end result is an `int`. – Kayaman Aug 22 '18 at 19:33
  • Thanks it seems that this https://stackoverflow.com/a/9816020/4777993 is the answer, I will now look up how this applies to other types. – Ben Aug 22 '18 at 19:46

2 Answers2

1

You cast to byte just the first number i and not the whole sum. You have to add the brackets:

byte z = (byte) (i+b);
Nikolas Charalambidis
  • 40,893
  • 16
  • 117
  • 183
1

Plus always returns int. So you need to explicitly typecast whole expression to byte.

(byte)(i+b)
NumeroUno
  • 1,100
  • 2
  • 14
  • 34