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
- A. L1 and L5
- B. L1, L5 and L7
- C. L1, L4, L5 and L7
- 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
- Which of these four fragments compiles? (FileReader's constructor throws FileNotFoundException, a subclass of IOException.) java // A try…
- What is printed? java class R implements AutoCloseable { public void close() { throw new IllegalStateException("close"); } } // in main…
- What is printed? java class T { static int a = T.b + 1; static int b = 5; static int c = b + 1; } // in main: System.out.print(T.a + " " +…
- What is printed? java class K { static final int C = 10; static final Integer D = 20; static { System.out.print("K "); } } // in main…
- Which lines fail to compile? java interface I { static String id() { return "I"; } default String name() { return "N"; } } class C…
- What is printed? cpp struct B { virtual string who() const { return "B"; } }; struct D : B { string who() const override { return "D"; }…