ProgrammingHardProduct-company placement · Java
What is printed?
What is printed?
// static method of the main class:
static void swap(int[] a, int[] b) {
int[] t = a; a = b; b = t;
a[0] = 100;
}
// in main:
int[] x = {1}, y = {2};
swap(x, y);
System.out.print(x[0] + " " + y[0]);- A. 100 2
- B. 1 100
- C. 2 1
- D. 100 1
Correct answer: B. 1 100
Java passes references by value: swapping the parameters does not affect x and y. After the swap, parameter a refers to y's array, so a[0] = 100 modifies y.
More OOP with C++ and Java questions
- What is printed? java Object o = "hi"; String s = (String) o; Integer n = null; System.out.print((n instanceof Integer) + " " + (o…
- What is printed? java class A { static int v = 1; static int get() { return v; } } class B extends A { static int v = 2; } // in main…
- What happens when this code is compiled? java try { new java.io.FileReader("x.txt"); } catch (Exception e) { System.out.print("E"); }…
- What is printed? java // static method of the main class: static int f() { try { throw new RuntimeException("t"); } finally { return 7; }…
- What is printed? java try { try { throw new IllegalStateException("A"); } finally { throw new IllegalArgumentException("B"); } } catch…
- What is printed? java class K { static int v = 10 / Integer.parseInt("0"); } // in main: try { System.out.print(K.v); } catch…