ProgrammingVery hardProduct company interview · GATE level
What is printed?
What is printed?
// static methods of the main class:
static void f(long x) { System.out.print("long "); }
static void f(Integer x) { System.out.print("Integer "); }
static void f(Object x) { System.out.print("Object "); }
static void f(int... x) { System.out.print("varargs "); }
// in main:
f(3);
f('c');
f(3.0);
f(Integer.valueOf(3));
f();- A. long long Object Integer varargs
- B. Integer long Object Integer varargs
- C. long long varargs Integer varargs
- D. long Integer Object Object varargs
Correct answer: A. long long Object Integer varargs
Java resolves overloads in phases: first without boxing or varargs, then with boxing, then with varargs. f(3): int widens to long in phase 1, so long beats Integer, which needs boxing. f('c'): char widens to long. f(3.0): double cannot narrow to long, so phase 1 finds nothing; phase 2 boxes to Double, which matches Object. f(Integer.valueOf(3)): both Integer and Object apply in phase 1 and Integer is more specific. f() matches only the varargs method.
More OOP with C++ and Java questions
- What happens when this code runs? java List<String> strs = new ArrayList<>(); strs.add("a"); List raw = strs; raw.add(42)…
- What is printed? java final String a = "Ja"; String b = "Ja"; String x = a + "va"; String y = b + "va"; String z = y.intern()…
- What is printed? java class K { int id; K(int id) { this.id = id; } public boolean equals(Object o) { return o instanceof K && ((K) o).id…
- What happens when this code runs? java Integer n = null; boolean flag = true; Integer a = flag ? n : Integer.valueOf(0)…
- Which lines fail to compile? java short s = 1; s = s + 1; // L1 s += 1; // L2 char c = 'A'; c++; // L3 final int k = 10; byte b1 = k; //…
- Which of these four fragments compiles? (FileReader's constructor throws FileNotFoundException, a subclass of IOException.) java // A try…