ProgrammingVery hardProduct-company placement · Java
Which lines fail to compile?
Which lines fail to compile?
String s = "x"; Number n = 1; Runnable r = () -> { }; Object o = s;
boolean a = s instanceof Integer; // L1
boolean b = n instanceof Integer; // L2
boolean c = r instanceof String; // L3
boolean d = o instanceof Runnable; // L4- A. L1 only
- B. L1, L3 and L4
- C. L1 and L3
- D. L3 only
Correct answer: C. L1 and L3
instanceof is a compile-time error when the cast could never succeed. String and Integer are unrelated classes (L1); String is final and does not implement Runnable, so no Runnable can be a String (L3). Number and Object can hold the tested types.
More OOP with C++ and Java questions
- What is printed? java // Java 16 or later record R(int[] a) { } record S(List<Integer> l) { } // in main: System.out.print(new R(new…
- What is printed? java enum Op { ADD { int apply(int a, int b) { return a + b; } }, MUL { int apply(int a, int b) { return a b; } }…
- What is printed? java enum Day { MON, TUE, WED } // in main: Map<Day, Integer> m = new EnumMap<>(Day.class); m.put(Day.WED, 3)…
- Which line fails to compile? java List<String>[] a = new List<String>[2]; // L1 List<?>[] b = new List<?>[2]; // L2 List<String>[] c = new…
- Which line fails to compile? java class Box<T extends Number> { double d(T t) { return t.doubleValue(); } } // in main: Box<Integer> a =…
- Which class compiles? java class K1 { static { throw new RuntimeException(); } } class K2 { static { if (true) throw new…