Given public class Fishing { byte b1 = 4; int i1 = 123456; long L1 = (long) i1; //Line A short s2 = (short) i1; //Line B byte b2 = (byte) i1; //Line C int i2 = (int)123.456; //Line D byte b3 = b1 + 7; //Line E } Which lines WILL NOT compile? (Choose all that apply)

Respuesta :

Answer:

Line E.

Explanation:

The  given program is as follows:

public class Fishing {

   byte b1 = 4; int i1 = 123456; long L1 = (long) i1;   //Line A

   short s2 = (short) i1;     //Line B

   byte b2 = (byte) i1;     //Line C

   int i2 = (int)123.456;    //Line D

   byte b3 = b1 + 7;     //Line E

   }

In the above code Line E will not compile and give following compilation error:

error: incompatible types: possible lossy conversion from int to byte

This error is coming because in Java b1 + 7 will be interpreted as int variable expression. Therefore in order to make code of Line E work the expression should be type casted as byte.  

The correct code will be as follows:

public class Fishing {

   byte b1 = 4; int i1 = 123456; long L1 = (long) i1;   //Line A

   short s2 = (short) i1;     //Line B

   byte b2 = (byte) i1;     //Line C

   int i2 = (int)123.456;    //Line D

   byte b3 = (byte)(b1 + 7);     //Line E

   }