ProgrammingModerateAmazon/Microsoft SDE MCQ · Java placement
Which line fails to compile?
Which line fails to compile?
int base = 10;
int step = 1;
step = 2;
Function<Integer, Integer> f = x -> x + base; // line 1
Function<Integer, Integer> g = x -> x + step; // line 2
Runnable r = () -> { int base2 = base; }; // line 3- A. Line 1
- B. Line 3
- C. Line 2
- D. Lines 1 and 3
Correct answer: C. Line 2
A lambda may only capture local variables that are final or effectively final. base is never reassigned, so lines 1 and 3 are fine; step is reassigned, so capturing it on line 2 is an error.
More OOP with C++ and Java questions
- What is printed? java // static methods of the main class: static void f(Object o) { System.out.print("O"); } static void f(int... a) {…
- What is printed? java char c = 'a'; c += 1; System.out.print(('a' + 1) + "" + (char) ('a' + 1) + c);
- What is printed? java Object o = null; String s = (String) o; System.out.print(s + (o instanceof Object) + (s == null));
- What is printed? java List<String> l = new ArrayList<>(List.of("pear", "fig", "apple", "kiwi"))…
- Why does this class fail to compile? java class Util { static void f(List<String> l) { } static void f(List<Integer> l) { } }
- What is printed? java record Pt(int x, int y) { } // in main: Set<Pt> s = new HashSet<>(); s.add(new Pt(1, 2)); s.add(new Pt(1, 2))…