Creating and Using Arrays practice questions

From OCA Java SE 7 (1Z0-803) · 23 questions on this topic

Creating and Using Arrays practice questions from OCA Java SE 7 (1Z0-803). This pack has 23 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 output of the following program? ```java import java.util.ArrayList; public class Main { public static void main(String[] args) { ArrayList<String> l = new ArrayList<String>(); l.add("a"); l.add("b"); l.add(1, "c"); l.set(0, "d"); System.out.println(l + " " + l.size()); } } ```

    1. A. [d, b, c] 3

      This treats add(1, "c") as appending "c" at the end rather than inserting it at index 1. The insert shifts "b" right to give [a, c, b], so "c" is not last.

    2. B. [d, c, b] 3Correct answer

      add("a"), add("b") give [a, b]; add(1, "c") inserts at index 1 shifting "b" right to [a, c, b]; set(0, "d") replaces index 0 without changing size, giving [d, c, b] with size 3 (JavaDoc 7 — ArrayList.add(int, E) / set(int, E)).

    3. C. [c, d, b] 3

      This misplaces the inserted and replaced elements. "c" is inserted at index 1 (not index 0), and set(0, "d") replaces index 0, so "d" must be first, giving [d, c, b].

    4. D. [d, c, b] 4

      The contents are right, but set(0, "d") replaces an existing element rather than adding one, so the size stays 3, not 4. Only add grows the list.

    Explanation

    add("a"), add("b") → [a, b]. add(1, "c") INSERTS at index 1, shifting b right → [a, c, b]. set(0, "d") REPLACES the element at index 0 without changing the size → [d, c, b], size 3. add-with-index grows the list; set never does.

  2. Question 2

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

    1. A. 3

      This assumes new int[][3] allocates an array whose length is 3. But dimensions must be filled from the left; specifying the inner size while leaving the outer empty is a syntax error, so nothing runs.

    2. B. 0

      There is no run in which length is 0: new int[][3] is a syntax error, so the program never compiles to print anything.

    3. C. Compilation failsCorrect answer

      Dimensions must be filled from the left. new int[3][] is legal, but new int[][3] specifies an inner dimension while leaving the outer empty — there is no outer array to hold the rows, so it is a syntax error (JLS 7 §15.10).

    4. D. An exception is thrown at runtime

      The failure is at compile time: new int[][3] is a syntax error, so execution never starts and no runtime exception can be thrown.

    Explanation

    Dimensions must be filled from the LEFT: `new int[3][]` is legal (outer array allocated, rows deferred), but `new int[][3]` is a syntax error — you can't specify an inner dimension while leaving the outer one empty, because there would be no outer array to hang the rows on.

  3. Question 3

    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<String>(); l.add("x"); l.add("y"); l.add("x"); System.out.println(l.indexOf("x") + " " + l.contains("z") + " " + l.size()); } } ```

    1. A. 2 false 3

      indexOf returns the first match at index 0, not the later duplicate at index 2.

    2. B. 0 false 2

      Duplicates are allowed, so all three adds count and size is 3, not 2.

    3. C. 0 true 3

      "z" was never added, so contains("z") is false, not true.

    4. D. 0 false 3Correct answer

      indexOf("x") returns the first match 0, contains("z") is false, and all three adds give size 3.

    Explanation

    Duplicates are allowed, so all three adds count (size 3 — `0 false 2` is wrong). indexOf returns the FIRST match (index 0, not the later duplicate at 2). "z" was never added, so contains is false.

  4. Question 4

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

    1. A. 3 2 0

      This treats the unassigned row grid[2] as if it defaulted to the numeric value 0. But grid[2] is a row reference (an int[]), and an unassigned reference defaults to null, printing "null", not 0.

    2. B. It throws a NullPointerException

      grid[2] is null, but it is only concatenated into a string, never dereferenced (no grid[2].length), so printing it yields "null" without any NullPointerException.

    3. C. Compilation fails because the second dimension is missing

      new int[3][] is legal: it allocates only the outer array and leaves the row slots null to be filled later. Deferring the inner dimension is allowed, so there is no compile error.

    4. D. 3 2 nullCorrect answer

      The outer array has length 3; row grid[1] was assigned two elements (length 2); row grid[2] was never assigned, so it stays null and prints as "null" via concatenation (JLS 7 §10.3, §15.10).

    Explanation

    A 2D array is an array OF arrays, and `new int[3][]` legally allocates only the outer array (`Compilation fails because the second dimension...` is wrong) — its three row slots default to null. Rows 0 and 1 are then assigned ragged lengths; row 2 stays null. Printing the reference grid[2] via concatenation shows "null" without dereferencing it (no NPE).

  5. Question 5

    A method needs the number of elements in three containers: an array `a`, a String `s`, and an ArrayList `list`. Which expression set is correct?

    1. A. a.length(), s.length(), list.size()

      Arrays expose length as a final field, not a method; a.length() does not exist. Writing it with parentheses treats the array field like String's length() method.

    2. B. a.length, s.length, list.length

      The array part is right, but String uses the method length() (not a field) and ArrayList uses size() — neither s.length nor list.length exists.

    3. C. a.size(), s.length(), list.size()

      Arrays have no size() method; they use the length field. Only collections like ArrayList expose size(), so a.size() is invalid.

    4. D. a.length, s.length(), list.size()Correct answer

      Each container uses its own API: arrays expose the field length, String has the method length(), and ArrayList has the method size() — this set matches all three correctly (JLS 7 §10.7; JavaDoc 7).

    Explanation

    Three different APIs for the same idea: arrays expose a final FIELD `length`; String has a METHOD `length()`; collections like ArrayList have a METHOD `size()`. Mixing them up is a deliberate exam trap — there is no a.length(), s.length, or list.length.

  6. Question 6

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

    1. A. 2

      This assumes new int[2]{1, 2} is valid and a[1] evaluates to 2. But giving an explicit size and an initializer together is a syntax error, so the code never runs.

    2. B. 1

      This both assumes the illegal size-plus-initializer form compiles and misreads the index; a[1] would be 2 anyway, but the real point is that the expression is a syntax error.

    3. C. Compilation failsCorrect answer

      You may give an explicit size (new int[2]) or an initializer (new int[]{1, 2}), but never both — the initializer already fixes the length, so an explicit dimension alongside it is a syntax error (JLS 7 §15.10).

    4. D. An exception is thrown at runtime

      The failure is at compile time, not runtime: combining an explicit size with an initializer is a syntax error, so execution never begins and no exception is thrown.

    Explanation

    You may give an explicit size (`new int[2]`) or an initializer (`new int[]{1, 2}`), but never BOTH — the initializer already determines the length, so an explicit dimension alongside it is a syntax error.

  7. Question 7

    What is the output of the following program? ```java public class Main { public static void main(String[] args) { int[] p = {1, 2}; int[] q = {1, 2}; System.out.println((p == q) + " " + p.equals(q) + " " + java.util.Arrays.equals(p, q)); } } ```

    1. A. false true true

      This assumes p.equals(q) compares contents. Arrays do not override equals(), so it falls back to Object's identity comparison and returns false for two distinct arrays.

    2. B. true true true

      p and q are two separately created array objects, so the reference comparison p == q is false; identical contents do not make them the same object.

    3. C. false false trueCorrect answer

      p == q is false (distinct objects); p.equals(q) is false (arrays inherit Object identity equals); only Arrays.equals(p, q) compares element contents and returns true (JavaDoc 7 — java.util.Arrays.equals).

    4. D. false false false

      The first two are indeed false, but Arrays.equals(p, q) does a true element-by-element content comparison, and the equal contents make it true, not false.

    Explanation

    p and q are two distinct array objects, so == is false. Arrays don't override equals() — it's inherited identity comparison from Object, so p.equals(q) is also false. Content comparison needs the utility method Arrays.equals(p, q), which is true here.

  8. Question 8

    What is the output of the following program? ```java import java.util.ArrayList; public class Main { public static void main(String[] args) { ArrayList<Integer> list = new ArrayList<Integer>(); list.add(5); list.add(10); list.add(15); list.remove(1); list.remove(Integer.valueOf(5)); System.out.println(list); } } ```

    1. A. [15]Correct answer

      remove(1) selects the remove(int index) overload and deletes the element at index 1 (value 10), leaving [5, 15]; remove(Integer.valueOf(5)) selects remove(Object) and deletes the first element equal to 5, leaving [15] (JavaDoc 7 — ArrayList.remove).

    2. B. [5, 15]

      This stops after remove(1) and assumes remove(Integer.valueOf(5)) does nothing. But that call removes the object 5, so 5 is also deleted, leaving just [15].

    3. C. [10, 15]

      This misreads remove(1) as removing the value 1 rather than the element at index 1. remove(1) uses the int-index overload and removes 10, not the value 1.

    4. D. [10]

      This mixes up which overload each call selects; remove(1) removes index 1 (value 10) and remove(Integer.valueOf(5)) removes the value 5, which together leave [15], not [10].

    Explanation

    remove(1) matches the remove(int index) overload — it removes the element AT INDEX 1 (the value 10), leaving [5, 15]. remove(Integer.valueOf(5)) forces the remove(Object) overload — it removes the first element EQUAL to 5, leaving [15]. The int-vs-Integer overload distinction is the whole point of this pattern.

Practise all 23 Creating and Using Arrays questions

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

Open OCA Java SE 7

Other topics in this pack