ProgrammingVery hardProduct company interview · GATE level

Which lines fail to compile?

Which lines fail to compile?
short s = 1;
s = s + 1;        // L1
s += 1;           // L2
char c = 'A';
c++;              // L3
final int k = 10;
byte b1 = k;      // L4
int m = 10;
byte b2 = m;      // L5
byte b3 = 'a';    // L6
char c2 = b1;     // L7
  1. A. L1 and L5
  2. B. L1, L5 and L7
  3. C. L1, L4, L5 and L7
  4. D. L1, L5, L6 and L7

Correct answer: B. L1, L5 and L7

L1: s + 1 is an int, and assigning an int variable expression to a short needs a cast. L2 and L3 compile because compound assignment and ++ include an implicit cast. L4 and L6 compile because the right side is a constant expression (k is a final int initialised with 10; 'a' is 97) whose value fits in a byte. L5 fails because m is not a constant. L7 fails because byte to char is not an allowed assignment conversion (byte is signed, char unsigned), even though both are small types.

More OOP with C++ and Java questions

Exams that ask this topic