ProgrammingHardProduct-company placement · Java
What is printed?
What is printed?
Object[] arr = new String[2];
arr[0] = "ok";
try { arr[1] = 42; System.out.print("stored"); }
catch (ArrayStoreException e) { System.out.print("ASE"); }
System.out.print(" " + arr.length);- A. stored 2
- B. Compile-time error at arr[1] = 42
- C. ASE 2
- D. A ClassCastException is thrown
Correct answer: C. ASE 2
Arrays are covariant, so String[] can be referenced as Object[] and arr[1] = 42 compiles; at run time the array knows it is a String[] and throws ArrayStoreException.
More OOP with C++ and Java questions
- What is printed? java int[] a = {1, 2}, b = {1, 2}; int[][] p = {{1}}, q = {{1}}; System.out.print(a.equals(b) + " " + Arrays.equals(a, b)…
- What is printed? java String s = null; s += "x"; String t = "a" + null + 1 + 2; System.out.print(s + " " + t);
- What is printed? java StringBuilder sb = new StringBuilder("abcdef"); sb.insert(2, "XY").delete(5, 7).reverse().setCharAt(0, 'Z')…
- What is printed? java String s = "level"; String t = s.replace('l', 'p'); System.out.print(t + " " + (s.replace('z', 'q') == s) + " " + s);
- What is printed? java String s = "hello"; System.out.print("[" + s.substring(5) + "]"); System.out.print(s.substring(6));
- What is printed? java Integer a = 1000; Integer b = a; a++; System.out.print(a + " " + b + " " + (a == b));