ProgrammingHardProduct-company placement · Java
Which line fails to compile?
Which line fails to compile?
List<?> l = new ArrayList<String>();
l.add(null); // L1
l.add("x"); // L2
Object o = l.isEmpty() ? null : l.get(0); // L3- A. L1 and L2
- B. L2 and L3
- C. None
- D. L2 only
Correct answer: D. L2 only
List<?> means 'a list of some unknown type': the only value known to fit is null. Reading elements as Object is always safe.
More OOP with C++ and Java questions
- Which line fails to compile? java class Fruit implements Comparable<Fruit> { public int compareTo(Fruit o) { return 0; } } class Apple…
- Which line fails to compile? java // Java 16 or later Object o = "hello"; if (o instanceof String s && s.length() > 3)…
- What is printed? java Set<Short> s = new HashSet<>(); for (short i = 0; i < 5; i++) { s.add(i); s.remove(i - 1); }…
- What is printed? java Map<Long, String> m = new HashMap<>(); m.put(1L, "one"); System.out.print(m.get(1) + " " + m.get(1L) + " " +…
- What is printed? java List<Character> l = new ArrayList<>(List.of('a', 'b')); System.out.print(l.contains('a') + " " + l.contains(97) + "…
- What is printed? java Function<Integer, Integer> f = x -> x + 1; Function<Integer, Integer> g = x -> x 2…