Creating and Using Arrays practice questions

From OCA Java SE 8 (1Z0-808) · 19 questions on this topic

Creating and Using Arrays practice questions from OCA Java SE 8 (1Z0-808). This pack has 19 questions tagged Creating and Using Arrays, drawn from its timed mock exams. 8 of them are worked through in full below — the question, every option, why each is right or wrong, and the explanation.

Worked examples for Creating and Using Arrays

  1. Question 1

    What is the result of compiling the following program? ```java public class Main { public static void main(String[] args) { int[] x = new int[]; System.out.println(x.length); } } ```

    1. A. 0

      Assumes the code compiles and prints a default length of 0; without a size or initializer the array creation never compiles.

    2. B. Compilation failsCorrect answer

      `new int[]` supplies neither a dimension nor an initializer, so the compiler cannot determine a length and rejects the code (JLS 8 §15.10.1).

    3. C. It compiles and length defaults to 0

      There is no default-to-zero-length rule for an array creation missing its size; the code fails to compile rather than defaulting.

    4. D. An exception is thrown at runtime

      The error is caught at compile time, so the program never runs and no exception is thrown.

    Explanation

    `new int[]` must be told its size — either an explicit dimension (new int[3]) or an initializer (new int[]{1, 2}). With neither, the array's length is unknowable and the compiler rejects it.

  2. Question 2

    Which of the following statements compiles without error?

    1. A. Object[] o = new String[1];Correct answer

      Arrays are covariant: because String is a subtype of Object, String[] is a subtype of Object[], so the reference widens and this compiles (JLS 8 §4.10.3). Java defers the risk to run time — storing a non-String through the Object[] view raises ArrayStoreException.

    2. B. List<Object> l = new ArrayList<String>();

      Applies array covariance to generics, which are invariant (JLS 8 §4.5): the String/Object relationship creates no relationship between List<String> and List<Object>, so javac reports `incompatible types: ArrayList<String> cannot be converted to List<Object>`. A wildcard such as List<? extends Object> would be needed for the widening.

    3. C. String[] s = new Object[1];

      Assumes array covariance also narrows. It only widens (String[] to Object[]), never the reverse — an Object[] may hold anything, so exposing it as a String[] would be unsound. javac reports `incompatible types: Object[] cannot be converted to String[]`; an explicit cast would then fail at run time.

    4. D. List<String> l = new ArrayList<Object>();

      Invariance pointed the other way, for someone who concluded the generic rule was directional. With generics NEITHER direction is implicit: javac reports `incompatible types: ArrayList<Object> cannot be converted to List<String>`.

    Explanation

    Arrays are COVARIANT and generics are INVARIANT. That single asymmetry decides all four statements, and it is the contrast the exam keeps coming back to. `Object[] o = new String[1];` compiles: because `String` is a subtype of `Object`, `String[]` is a subtype of `Object[]`, so the array reference widens. Java pays for this at run time instead -- store a non-String into that array through the `Object[]` view and you get an `ArrayStoreException`. The compiler lets it through; the JVM catches it. Why the others are wrong: `List<Object> l = new ArrayList<String>();` is the generic mirror of the statement that works, and it is exactly what invariance forbids. No relationship between `String` and `Object` creates any relationship between `List<String>` and `List<Object>`; they are unrelated types, full stop. javac says `incompatible types: ArrayList<String> cannot be converted to List<Object>`. Use `List<? extends Object>` if you want the widening. `String[] s = new Object[1];` assumes covariance runs downward too. It does not. Covariance widens (`String[]` to `Object[]`), never narrows -- an `Object[]` may hold anything, so handing it out as a `String[]` would be unsound. This one needs an explicit cast, and the cast would then fail at run time. javac: `incompatible types: Object[] cannot be converted to String[]`. `List<String> l = new ArrayList<Object>();` is invariance again, pointed the other way, for the student who concluded the rule was directional. It is not: with generics NEITHER direction is implicit. Exam tip: the fastest way through a question like this is to ask, per line, "array or generic?" Arrays widen and blow up later; generics refuse to widen at all. And remember the reason the language is inconsistent here -- arrays predate generics, and their covariance is a hole that erasure could not afford to repeat.

  3. Question 3

    What is the result of compiling the following program? ```java public class Main { public static void main(String[] args) { int[] a = {1}; System.out.println(a.length()); } } ```

    1. A. 1

      Assumes a.length() is a valid call returning the element count; length is a field on arrays, so the parenthesized form never compiles and nothing is printed.

    2. B. 0

      The array holds one element anyway, but more fundamentally the call a.length() does not compile, so no value is ever printed.

    3. C. Compilation failsCorrect answer

      Arrays expose length as a FIELD, not a method, so a.length() gets "cannot find symbol: method length()" (JLS 8 §10.7); the parenthesized form belongs to String and size() to collections.

    4. D. An exception is thrown at runtime

      The missing method is a compile-time symbol error, so the program never runs and no runtime exception occurs.

    Explanation

    Arrays expose length as a FIELD, not a method — a.length() gets "cannot find symbol: method length()". The parenthesized form belongs to String; size() belongs to collections.

  4. Question 4

    What is the output of the following program? ```java public class Main { public static void main(String[] args) { int[][] g = { {1, 2, 3}, {4, 5} }; System.out.println(g[1][1] + g[0][2]); } } ```

    1. A. 53

      Treats + as string concatenation of 5 and 3; both operands are ints, so + performs numeric addition instead.

    2. B. 7

      Comes from misreading one of the indexes — the values added are g[1][1] = 5 and g[0][2] = 3, which sum to 8, not 7.

    3. C. It throws an ArrayIndexOutOfBoundsException

      Assumes the ragged shape (a 3-element row and a 2-element row) is illegal or out of range; the shape is legal and both indexes used are within their rows.

    4. D. 8Correct answer

      g[1][1] is 5 and g[0][2] is 3, and since both are ints the + operator adds them numerically to give 8 (JLS 8 §10.6).

    Explanation

    g[1][1] is 5 (second row, second column) and g[0][2] is 3. Both operands are ints, so + is numeric addition: 8 — not concatenation (`53`). The ragged shape is legal and both indexes are in range.

  5. Question 5

    What is the output of the following program? ```java import java.util.Arrays; import java.util.List; public class Main { public static void main(String[] args) { List<String> list = Arrays.asList("a", "b"); try { list.add("c"); System.out.println("added"); } catch (UnsupportedOperationException e) { System.out.println("fixed"); } } } ```

    1. A. fixedCorrect answer

      add() on the fixed-size list returned by Arrays.asList throws UnsupportedOperationException, which the catch handles by printing "fixed".

    2. B. added

      Assumes add() succeeds; the fixed-size list backed by the array forbids add(), so the "added" branch is never reached.

    3. C. Compilation fails because asList cannot take varargs

      Arrays.asList is declared with varargs and compiles fine; the failure here is a runtime UnsupportedOperationException, not a compile error.

    4. D. It throws an ArrayIndexOutOfBoundsException

      The exception is UnsupportedOperationException from the fixed-size list, not an ArrayIndexOutOfBoundsException; no index is out of range.

    Explanation

    Arrays.asList returns a FIXED-SIZE list backed by the array: set() works, but add() and remove() throw UnsupportedOperationException at runtime. Wrap it — new ArrayList<>(Arrays.asList(...)) — to get a growable copy.

  6. Question 6

    What is the output of the following program? ```java import java.util.ArrayList; public class Main { public static void main(String[] args) { ArrayList<String> l = new ArrayList<>(); l.add(null); l.add("x"); System.out.println(l.size() + " " + l.contains(null)); } } ```

    1. A. 1 false

      This assumes nulls are neither stored nor counted; ArrayList keeps them, counts them in size, and finds them with contains.

    2. B. It throws a NullPointerException

      The list handles null comparisons specially, so neither add(null) nor contains(null) throws.

    3. C. 2 trueCorrect answer

      ArrayList happily stores null elements and counts them in size (2), and contains(null) is supported and true (JavaDoc 8 — ArrayList).

    4. D. Compilation fails because null cannot be added

      null is a legal value for any reference-typed argument, so add(null) compiles.

    Explanation

    ArrayList happily stores null elements (`Compilation fails because null cannot be added` is wrong), counts them in size (2), and contains(null) is supported and true. No NPE — the list itself handles null comparisons specially.

  7. Question 7

    What is the output of the following program? ```java public class Main { public static void main(String[] args) { int[][] m = new int[4][2]; System.out.println(m.length + " " + m[3].length); } } ```

    1. A. 2 4

      This swaps the dimensions: the first is the outer array's length (4 rows) and the second each row's length (2).

    2. B. 4 2Correct answer

      The first dimension is the outer array's length (4 rows), the second each row's length (2), and m[3] is the last valid row (JLS 8 §10.3).

    3. C. 8 2

      length never multiplies the dimensions together — the outer array simply has 4 elements.

    4. D. It throws an ArrayIndexOutOfBoundsException

      With 4 rows, indexes 0 through 3 are valid, so m[3] is in range.

    Explanation

    The FIRST dimension is the outer array's length (4 rows), the second each row's length (2). m[3] is the last valid row — in range. length never multiplies dimensions (not `8 2`).

  8. Question 8

    What is the output of the following program? ```java public class Main { public static void main(String[] args) { int[] a = {1, 2}; int[] b = a.clone(); b[0] = 9; System.out.println(a[0] + " " + b[0]); } } ```

    1. A. 1 9Correct answer

      clone() on an array produces an independent copy, so writing through the copy leaves the original untouched: 1 vs 9 (JLS 8 §10.7).

    2. B. 9 9

      That is the behavior of plain `int[] b = a;`, which aliases the same array; clone() copies instead.

    3. C. 1 1

      The write to the copy does take effect — it simply does not reach the original array.

    4. D. Compilation fails because arrays have no clone method

      Every array supports clone(), so this compiles fine.

    Explanation

    clone() on an array produces an independent COPY (`Compilation fails because arrays have no clone method` is wrong — every array supports it), so writing through b leaves a untouched: 1 vs 9. Contrast with plain `int[] b = a;`, which aliases the same array (the `9 9` behavior).

Practise all 19 Creating and Using Arrays questions

OCA Java SE 8 has the full set, inside timed mock exams that mirror real exam conditions — every question with a worked explanation.

Open OCA Java SE 8

Other topics in this pack