ProgrammingVery hardProduct-company placement · Java
Which line fails to compile?
Which line fails to compile?
// Java 16 or later
Object o = "hello";
if (o instanceof String s && s.length() > 3) System.out.print(s.length()); // L1
if (o instanceof String t || t.isEmpty()) System.out.print("x"); // L2- A. L1 only
- B. Both
- C. Neither
- D. L2 only
Correct answer: D. L2 only
A pattern variable is in scope only where the match is definitely true. After && it is; on the right of || the left side was false, so t is not bound there.
More OOP with C++ and Java questions
- 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…
- What is printed? java List<String> l = new ArrayList<>(List.of("ccc", "ee", "a", "bb", "d"))…
- What is printed? java int[] c = {0}; Runnable r = () -> c[0]++; r.run(); r.run(); System.out.print(c[0]);