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));
    }
}
  1. A. [3, 2, 1]
  2. B. Compilation error: T cannot be inferred
  3. C. [2, 1, 3]
  4. 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

Exams that ask this topic