ProgrammingHardIBM · Deloitte pattern
What is printed?
What is printed?
class Util {
static <T> void swap(T[] arr, int i, int j) {
T tmp = arr[i];
arr[i] = arr[j];
arr[j] = tmp;
}
}
public class Main {
public static void main(String[] args) {
Integer[] arr = {1, 2, 3};
Util.swap(arr, 0, 2);
System.out.print(Arrays.toString(arr));
}
}- A. [3, 2, 1]
- B. Compilation error: T cannot be inferred
- C. [2, 1, 3]
- D. [1, 2, 3]
Correct answer: A. [3, 2, 1]
A generic method works uniformly for any reference array type; the compiler infers T=Integer from the call. swap exchanges index 0 and 2, turning {1,2,3} into {3,2,1}.
More OOP with C++ and Java questions
- What is printed? java public class Main { static <T extends Comparable<T>> T max(T a, T b) { return a.compareTo(b) >= 0 ? a : b; } public…
- Which statement is correct about this class? java public class Base { public void show() { } } class Sub extends Base { private void…
- Which statement is correct? java class Base { protected void configure() { } } class Derived extends Base { public void configure() { } }
- Which statement is correct? java final class Immutable { void f() { } } class Sub extends Immutable { }
- Which statement is correct? java class Base { final void process() { System.out.print("Base.process"); } } class Sub extends Base { void…
- What is printed? java class Outer { private int secret = 42; class Inner { int reveal() { return secret; } } } public class Main { public…