ProgrammingModerateProduct-company placement · Java
What is printed?
What is printed?
int[] arr = {1, 2, 3};
for (int x : arr) x *= 2;
System.out.print(Arrays.toString(arr));- A. [2, 4, 6]
- B. [1, 2, 3, 2, 4, 6]
- C. [1, 2, 3]
- D. Compile-time error: x is final
Correct answer: C. [1, 2, 3]
The enhanced for loop copies each element into the local variable x; changing x does not write back to the array.
More OOP with C++ and Java questions
- What is printed? java Set<String> s = new LinkedHashSet<>(List.of("a", "b", "c")); s.remove("a"); s.add("a"); s.add("b")…
- What is printed? java TreeMap<String, Integer> m = new TreeMap<>(); for (String k : new String[]{"9", "10", "100", "2"}) m.put(k…
- What is printed? java String r = Collections.max(List.of("pear", "fig", "banana", "kiwi"), Comparator.comparing(String::length))…
- Which line fails to compile? java int[] a = {3, 1, 2}; Integer[] b = {3, 1, 2}; Arrays.sort(b, Collections.reverseOrder()); // L1…
- Which line fails to compile? java class P { void hi() { } } class C extends P { void a() { super.hi(); } // L1 static void b() {…
- What is printed? java Object[] objs = {1, "a", 2.0, 'c'}; for (Object o : objs) System.out.print(o.getClass().getSimpleName());