CCNA Arrays Methods Questions

68 of 79 questions · Page 1/2 · Arrays Methods topic · Answers revealed

1
MCQmedium

A method 'public static void sort(int[] arr)' sorts the array in place. After calling 'sort(data)', the original array 'data' is changed. Which design issue does this demonstrate?

A.The method should use a wrapper class for the array.
B.The method should be declared as void to indicate modification.
C.The method should return a new array to avoid side effects.
D.The method should use pass-by-value to avoid modification.
AnswerC

Changing the original array can lead to unexpected behavior; returning a new array is a common practice.

Why this answer

Option C is correct because the method modifies the original array passed as an argument, which is a side effect. In Java, arrays are objects, and when passed to a method, the reference is passed by value, allowing the method to modify the array's contents. To avoid side effects and maintain immutability, the method should return a new sorted array instead of modifying the original.

Exam trap

The trap here is that candidates often confuse pass-by-value for objects with pass-by-reference, thinking that Java passes objects by reference, which would make modification expected, but the real issue is that the method's side effect violates the principle of least surprise and should be avoided by returning a new array.

How to eliminate wrong answers

Option A is wrong because using a wrapper class for the array does not prevent modification; the wrapper would still hold a reference to the same array, and the method could modify its contents. Option B is wrong because declaring the method as void does not indicate or prevent modification; it merely means the method does not return a value, but it can still modify the array in place. Option D is wrong because Java always uses pass-by-value for method arguments; for objects (including arrays), the reference is passed by value, so the method can modify the object's state, and this is not a design issue but a fundamental language behavior.

2
Multi-Selectmedium

Which TWO are valid ways to pass an array to a method in Java?

Select 2 answers
A.myMethod(new int[]{1,2,3});
B.int[] arr = {1,2,3}; myMethod(arr);
C.myMethod(1, 2, 3);
D.myMethod(int[] {1,2,3});
E.myMethod(new int[5] {1,2,3,4,5});
AnswersA, B

Correct anonymous array creation.

Why this answer

Option A is correct because `new int[]{1,2,3}` is an anonymous array creation expression that creates a new int array and passes it directly to the method. This syntax is valid in Java for passing an array literal without a variable. Option B is correct because it declares an array variable `arr` initialized with an array initializer `{1,2,3}` (which is allowed only in a declaration statement) and then passes that reference to the method, which is a standard way to pass an array.

Exam trap

The trap here is that candidates often confuse array initializer syntax with array creation syntax, mistakenly thinking `int[] {1,2,3}` or `new int[5] {1,2,3,4,5}` are valid, when Java requires either a declaration with an initializer or an anonymous array creation with `new` and no size specifier.

3
Multi-Selecteasy

Which TWO statements are true about method overloading in Java?

Select 2 answers
A.Overloaded methods must have the same number of parameters.
B.Overloaded methods can have different parameter lists.
C.Overloaded methods must have the same name.
D.Overloaded methods must have different return types.
E.Overloaded methods can have different names.
AnswersB, C

Different number or type of parameters.

Why this answer

Option B is correct because method overloading in Java allows multiple methods to share the same name but have different parameter lists (different number, type, or order of parameters). This enables compile-time polymorphism, where the compiler selects the appropriate method based on the arguments provided at the call site.

Exam trap

The trap here is that candidates often confuse method overloading with method overriding, mistakenly thinking return types must differ or that parameter counts must be identical, when in fact overloading only requires different parameter lists and the same method name.

4
MCQeasy

Given the array declaration: int[] data = new int[5];, what is the value of data[2] after initialization?

A.2
B.0
C.false
D.null
AnswerB

Default value for int array elements.

Why this answer

In Java, when an array of primitive type `int` is created using `new int[5]`, all elements are automatically initialized to the default value for `int`, which is `0`. Therefore, `data[2]` (the third element) holds the value `0` after initialization.

Exam trap

Oracle often tests the distinction between default values for primitives (e.g., `0` for `int`) versus objects (`null`) and the misconception that array elements are initialized to their index number or left uninitialized.

How to eliminate wrong answers

Option A is wrong because `2` is not the default value for an `int` array element; default initialization assigns `0`, not the index number. Option C is wrong because `false` is the default value for `boolean` arrays, not `int` arrays. Option D is wrong because `null` is the default value for object reference arrays, not for primitive `int` arrays.

5
Multi-Selectmedium

Which three statements about method overloading are true? (Select three.)

Select 3 answers
A.Overloaded methods can have different return types.
B.Overloaded methods cannot have different access modifiers.
C.Overloaded methods can have different access modifiers.
D.Overloaded methods can have the same parameter list as long as the return type differs.
E.Overloaded methods must have different parameter lists.
AnswersA, C, E

Return type can differ, but it is not sufficient to distinguish overloaded methods.

Why this answer

Option A is correct because method overloading in Java allows methods to have different return types, provided they have different parameter lists. The return type alone is not sufficient to distinguish overloaded methods, but it can vary as long as the parameter lists differ.

Exam trap

The trap here is that candidates often mistakenly think return type alone can distinguish overloaded methods, leading them to select Option D, but the Java compiler requires different parameter lists for overloading.

6
MCQeasy

Consider the following code that attempts to swap the first two elements of an array using a method: public static void swap(int[] arr) { int temp = arr[0]; arr[0] = arr[1]; arr[1] = temp; } public static void main(String[] args) { int[] values = {1, 2}; swap(values); System.out.println(values[0] + " " + values[1]); } What is the output?

A.2 1
B.The code does not compile.
C.1 2
D.A runtime exception occurs.
AnswerA

The method modifies the array elements, so after swap, values[0] becomes 2 and values[1] becomes 1.

Why this answer

Option A is correct because the `swap` method receives a reference to the array, so modifications to its elements (via index assignment) affect the original array. After swapping, `values[0]` becomes 2 and `values[1]` becomes 1, producing the output "2 1".

Exam trap

Cisco often tests the misconception that Java passes objects by value in a way that prevents modification, leading candidates to incorrectly believe the array remains unchanged (Option C) or that the code fails to compile (Option B).

How to eliminate wrong answers

Option B is wrong because the code compiles successfully: the `swap` method is correctly defined with an `int[]` parameter, and the call `swap(values)` passes a compatible array reference. Option C is wrong because it assumes the swap did not occur, which would only happen if Java passed arrays by value (it passes the reference by value, but the array object is shared). Option D is wrong because no runtime exception occurs: the array has exactly two elements, so indices 0 and 1 are valid, and the swap logic is safe.

7
MCQhard

Given the method: 'public static void swapFirstTwo(int[] arr) { int temp = arr[0]; arr[0] = arr[1]; arr[1] = temp; }'. What is the effect of calling this method with an array of length 1?

A.An ArrayIndexOutOfBoundsException is thrown.
B.The first element is swapped with itself.
C.A new array with length 2 is returned.
D.The array remains unchanged.
AnswerA

Index 1 is out of bounds for length 1.

Why this answer

The method accesses arr[0] and arr[1] without checking the array length. When called with an array of length 1, arr[1] does not exist, so the JVM throws an ArrayIndexOutOfBoundsException at runtime. This is because Java arrays are zero-indexed and bounds checking is performed at runtime.

Exam trap

Oracle often tests the misconception that a method with a void return type will silently do nothing or leave the array unchanged, when in fact an unchecked array access throws an exception.

How to eliminate wrong answers

Option B is wrong because the method does not check array length and attempts to access index 1, which is out of bounds for a length-1 array; no swap occurs. Option C is wrong because the method has a void return type and does not create or return any array. Option D is wrong because the method does not remain unchanged; it throws an exception before any modification can occur.

8
MCQeasy

What is the output when the main method is executed?

A.15.0
B.5.0
C.10.0
D.Compilation error: ambiguous method call
AnswerA

The int addition yields 15, promoted to double.

Why this answer

The correct answer is A (15.0) because the method call `sum(5, 10)` matches the overloaded method `sum(double a, double b)` after the integer literals are implicitly widened to `double`. The method returns `a + b`, which is `5.0 + 10.0 = 15.0`, and since the return type is `double`, the output is `15.0`.

Exam trap

Oracle often tests the concept of implicit widening conversion in method overloading, where candidates mistakenly think integer arguments must match an `int` parameter exactly or that the call would be ambiguous, when in fact the compiler silently widens to the only compatible `double` overload.

How to eliminate wrong answers

Option B (5.0) is wrong because it incorrectly assumes only the first argument is used or that the method subtracts rather than adds. Option C (10.0) is wrong because it mistakenly uses only the second argument or thinks the method returns the second parameter. Option D (compilation error: ambiguous method call) is wrong because there is no ambiguity: the only overloaded method that matches the two `int` arguments after widening is `sum(double, double)`, as no other `sum` method exists with two parameters.

9
MCQhard

Which statement about method overloading with array parameters is true?

A.A method with parameter int[] and another with parameter int... are overloaded.
B.A method with parameter int[] and another with parameter Integer[] are overloaded.
C.Two methods with the same name and same parameter types but different return types are considered overloaded.
D.A method with parameter int[] and another with parameter int[][0] are overloaded.
AnswerB

int[] and Integer[] are different types, so they can be overloaded.

Why this answer

Option B is correct because method overloading requires methods to have the same name but different parameter lists. int[] and Integer[] are different parameter types (primitive array vs. wrapper class array), so they satisfy the overloading requirement. The return type is irrelevant for overloading.

Exam trap

Oracle often tests the misconception that varargs (int...) and arrays (int[]) are distinct types for overloading, when in fact they are treated identically by the compiler.

How to eliminate wrong answers

Option A is wrong because int[] and int... (varargs) are not considered different parameter types for overloading; the compiler treats int... as int[] internally, so they are the same signature. Option C is wrong because overloading depends solely on parameter lists, not return types; two methods with identical parameter types but different return types cause a compilation error. Option D is wrong because int[][0] is not a valid parameter type in Java; array dimensions must be specified with brackets only, not indices.

10
Multi-Selecteasy

Which TWO are valid ways to declare and initialize an array of Strings?

Select 2 answers
A.String[] names = {"A", "B"}[];
B.String names[] = new String[2];
C.String[] names = new String[]{"A", "B"};
D.String[] names = {1, 2};
E.String names[] = {"A", "B"};
AnswersC, E

Valid anonymous array creation.

Why this answer

Option C is correct because it uses the valid syntax `new String[]{"A", "B"}` to both declare and initialize a String array in a single statement. This is the standard way to create an array with an anonymous array initializer when the declaration and initialization are combined.

Exam trap

Oracle often tests the distinction between array declaration syntax and the two valid initialization forms, trapping candidates who think `new String[2]` initializes with given values or that `{"A", "B"}[]` is a valid shortcut.

11
MCQeasy

Given an array arr of length 5, which code snippet correctly creates a copy using System.arraycopy?

A.System.arraycopy(arr, 0, copy, 0, arr.length);
B.int[] copy = Arrays.copyOf(arr, arr.length);
C.int[] copy = new int[arr.length]; System.arraycopy(arr, 0, copy, 0, arr.length);
D.int[] copy = arr.clone();
AnswerC

Initializes copy then uses arraycopy correctly.

Why this answer

Option C is correct because it first declares and initializes a destination array `copy` of the same length as `arr`, then calls `System.arraycopy(arr, 0, copy, 0, arr.length)` to copy all 5 elements from `arr` into `copy`. This is the only option that uses `System.arraycopy` correctly, as the method requires a pre-existing destination array.

Exam trap

Oracle often tests the requirement to use a specific method name exactly as stated in the question, so candidates mistakenly choose options that achieve the same result (like `Arrays.copyOf` or `clone()`) but do not use the mandated `System.arraycopy` call.

How to eliminate wrong answers

Option A is wrong because it references a variable `copy` that has not been declared or initialized, causing a compilation error. Option B is wrong because it uses `Arrays.copyOf`, not `System.arraycopy`, so it does not meet the requirement of the question. Option D is wrong because it uses `arr.clone()`, which is a different copying mechanism and not `System.arraycopy`.

12
MCQhard

A method 'public static int[] generate() { int[] result = new int[10]; for (int i = 0; i < result.length; i++) result[i] = i * 2; return result; }' is defined. Which statement correctly calls this method and stores the result?

A.int[] data = generate();
B.int[] data = new int[generate()];
C.int data = generate();
D.generate();
AnswerA

Correct assignment of int array variable.

Why this answer

Option A is correct because the method `generate()` returns an `int[]` (an array of integers), and the assignment `int[] data = generate();` correctly declares a reference variable of type `int[]` and assigns the returned array to it. The method is static, so it can be called directly from a static context without an instance.

Exam trap

Oracle often tests the distinction between array type and primitive type in method return values and variable declarations, trapping candidates who confuse `int[]` with `int` or who forget that a method call must assign the result to a compatible variable to be useful.

How to eliminate wrong answers

Option B is wrong because `new int[generate()]` attempts to use the return value of `generate()` as the size of a new array, but `generate()` returns an `int[]`, not an `int`, causing a compilation error. Option C is wrong because `int data = generate();` tries to assign an `int[]` to a primitive `int` variable, which is a type mismatch and will not compile. Option D is wrong because `generate();` calls the method but discards the returned array without storing it in any variable, so the result is lost and cannot be used later.

13
MCQhard

Given the code: public class Test { public static void change(int[] arr) { arr = new int[]{10, 20}; } public static void main(String[] args) { int[] arr = {1, 2}; change(arr); System.out.println(arr[0]); } } What is the output?

A.1
B.10
C.20
D.Compilation error
AnswerA

The method creates a new array and assigns it to the local parameter, but this assignment does not change the caller's reference, so arr[0] remains 1.

Why this answer

Option A is correct because in Java, array references are passed by value. Inside the `change` method, the local variable `arr` is reassigned to a new array, but this does not affect the original array reference in `main`. Therefore, `arr[0]` in `main` still refers to the original array element `1`.

Exam trap

Oracle often tests the distinction between modifying an object's state versus reassigning a reference, and the trap here is that candidates mistakenly believe reassigning the parameter inside the method will change the original array reference in the caller.

How to eliminate wrong answers

Option B is wrong because it assumes the reassignment inside `change` modifies the original array reference, but Java passes object references by value, so the original reference remains unchanged. Option C is wrong because it similarly assumes the reassignment affects the original array, and also selects the wrong element. Option D is wrong because the code compiles successfully; there is no syntax or type error.

14
MCQhard

Which approach does NOT create a new array that is independent of the original?

A.int[] copy = original;
B.int[] copy = Arrays.copyOf(original, original.length);
C.int[] copy = original.clone();
D.int[] copy = new int[original.length]; System.arraycopy(original, 0, copy, 0, original.length);
AnswerA

This simply copies the reference, so both variables point to the same array. Any modification to one affects the other.

Why this answer

Option A is correct because assigning one array variable to another does not create a new array; both variables reference the same array object.

15
Multi-Selecteasy

Which two of the following are valid ways to declare and initialize an array of integers? (Select two.)

Select 2 answers
A.int[] arr = new int[5]{1, 2, 3, 4, 5};
B.int[] arr = new int[5];
C.int[5] arr;
D.int arr[] = new int[]{1, 2};
E.int arr = new int[5];
AnswersB, D

Creates an array of size 5 with default values (0).

Why this answer

Options A and B are valid. Option A creates an array with default values (0). Option B creates an array with specified values.

Option C is invalid because you cannot specify both size and initializer. Option D has invalid syntax. Option E assigns an int to an int array variable.

16
MCQeasy

Which of the following is not a valid array variable declaration in Java?

A.int arr;
B.int[] arr[];
C.int[] arr;
D.int arr[];
AnswerA

Invalid: declares a primitive int, not an array.

Why this answer

Option A is correct because `int arr;` declares a simple integer variable, not an array. In Java, an array variable declaration must include square brackets ([]) to indicate the variable is an array type. Without brackets, the variable is a primitive or reference type, not an array.

Exam trap

Oracle often tests the distinction between array declarations and primitive variable declarations, trapping candidates who think `int arr;` is a valid array declaration because they overlook the missing brackets.

How to eliminate wrong answers

Option B is wrong because `int[] arr[];` is actually valid in Java — it declares a 2D array (array of int arrays), though it mixes bracket placement and is considered poor style. Option C is wrong because `int[] arr;` is a valid array declaration (brackets after the type). Option D is wrong because `int arr[];` is a valid array declaration (brackets after the variable name), a legacy C-style syntax that Java still supports.

17
MCQeasy

A method is needed to return a new array where each element is doubled. Which method signature correctly accomplishes this?

A.public int doubleArray(int[] input)
B.public int[] doubleArray(int[] input)
C.public int[] doubleArray(int input)
D.public void doubleArray(int[] input)
AnswerB

Correct return type and parameter.

Why this answer

Option B is correct because the method must return a new array with doubled values, so the return type must be `int[]` (an array of integers) and the parameter must be an `int[]` (the input array). This signature allows the method to accept an array, process each element, and return a new array of the same length with each element doubled.

Exam trap

Oracle often tests the distinction between returning a single value versus an array, and candidates may confuse the return type `int` with `int[]` or forget that the parameter must match the array type to process multiple elements.

How to eliminate wrong answers

Option A is wrong because the return type is `int` (a single integer) instead of `int[]` (an array), so it cannot return a new array. Option C is wrong because the parameter is `int input` (a single integer) instead of `int[] input` (an array), so it cannot accept an array to double each element. Option D is wrong because the return type is `void`, meaning the method returns nothing, but the requirement is to return a new array.

18
MCQmedium

A company manages employee data stored in an array of Employee objects. The HR application frequently needs to find an employee by ID. The current implementation uses a linear search through the array each time. Performance reports indicate that this search is becoming a bottleneck as the company grows. The array is not sorted, and the company does not want to sort it because the order is meaningful for display. The array is large and frequently updated. The development team considers several options to improve the search performance without changing the array order. Which approach should they implement?

A.Create a HashMap<Integer, Employee> that maps IDs to Employee objects, and maintain it alongside the array.
B.Use parallel streams to perform the search in parallel.
C.Convert the array to a HashSet of employee IDs and use contains() to check existence.
D.Use Arrays.binarySearch() on the array after temporarily sorting a copy each time.
AnswerA

Provides O(1) lookup and preserves array order.

Why this answer

Option B is the best because it provides O(1) lookup while preserving the original array order. Option A uses a HashSet of IDs but does not store Employee objects; you still need to retrieve the Employee. Option C requires sorting a copy each time, which is inefficient.

Option D may improve but still O(n) and adds overhead of parallelization.

19
MCQmedium

Given the code: int[] a = {1, 2, 3}; int[] b = {4, 5}; a = b; b[0] = 99; System.out.println(a[0]); What is the output?

A.3
B.1
C.99
D.4
AnswerC

After the assignment a = b, both references point to the same array; changing b[0] to 99 changes the shared array, so a[0] is 99.

Why this answer

After `a = b;`, both `a` and `b` reference the same array object. Modifying `b[0]` to 99 also changes `a[0]` because they share the same underlying array. Therefore, `a[0]` prints 99.

Exam trap

The trap here is that candidates mistakenly think `a = b` copies the array values, leading them to believe `a[0]` retains its original value of 1 or that the arrays remain independent.

How to eliminate wrong answers

Option A is wrong because 3 is the last element of the original array `a`, but after reassignment, `a` no longer points to that array. Option B is wrong because 1 was the first element of the original array `a`, but `a` now references `b`'s array. Option D is wrong because 4 was the original value of `b[0]`, but it was overwritten to 99 before the print statement.

20
Multi-Selectmedium

Which TWO methods correctly modify the passed array in place?

Select 2 answers
A.public void zeroOut(int[] a) { for (int i = 0; i < a.length; i++) a[i] = 0; }
B.public void incrementEach(int[] a) { for (int i = 0; i < a.length; i++) a[i]++; }
C.public void reset(int[] a) { a = new int[10]; }
D.public void swap(int[] a) { int[] temp = a; a = new int[1]; a[0] = temp[0]; }
E.public void setFirst(int[][] a) { a = new int[1][1]; a[0][0] = 5; }
AnswersA, B

Sets each element to 0, modifying the original array.

Why this answer

Option A is correct because it directly modifies each element of the passed array by assigning 0 to a[i] within the loop. In Java, when an array is passed to a method, the method receives a reference to the same array object, so changes to the array's elements are reflected in the caller's array.

Exam trap

Cisco often tests the misconception that reassigning the method parameter (e.g., a = new int[10]) modifies the original array, when in fact it only changes the local reference, leaving the original array untouched.

21
Multi-Selecthard

Which THREE statements are true about passing arrays to methods in Java?

Select 3 answers
A.If the method modifies elements of the array, the caller does not see the changes.
B.Varargs parameters allow passing zero or more arguments of the specified type.
C.If the method assigns a new array to the parameter, the caller's variable is updated.
D.The method receives a reference to the array.
E.Passing null as an array argument is allowed at compile time.
AnswersB, D, E

Varargs (T...) accept multiple arguments or an array.

Why this answer

Option B is correct because varargs (variable-length arguments) in Java allow a method to accept zero or more arguments of a specified type, using the syntax `Type... param`. This is syntactic sugar for an array parameter, and the method body treats it as an array. This enables flexible method invocation without requiring the caller to explicitly create an array.

Exam trap

The trap here is that candidates often confuse pass-by-value for object references with pass-by-reference, leading them to incorrectly believe that reassigning the parameter (Option C) or modifying elements (Option A) behaves the same way, when in fact only element modifications are visible to the caller.

22
MCQmedium

A developer writes a method that accepts a variable number of int arguments and returns their product. Which method signature correctly implements this?

A.public static int product(int[] nums)
B.public static int product(int nums...)
C.public static int product(int... nums)
D.public static int product(int... nums, int extra)
AnswerC

Varargs correctly declared.

Why this answer

Option C is correct because the syntax `int... nums` is the proper Java varargs syntax, allowing a method to accept zero or more `int` arguments, which are then treated as an array inside the method. This enables the developer to call `product(2, 3, 4)` or `product()` and compute the product by iterating over the array.

Exam trap

Oracle often tests the requirement that varargs must be the last parameter, and the trap here is that candidates might think `int nums...` is valid or that a regular array parameter qualifies as variable arguments.

How to eliminate wrong answers

Option A is wrong because it requires the caller to explicitly create and pass an `int[]` array, not a variable number of arguments. Option B is wrong because the ellipsis must come before the parameter name, not after; `int nums...` is invalid syntax. Option D is wrong because varargs must be the last parameter in the method signature; placing `int extra` after `int... nums` causes a compilation error.

23
MCQmedium

A developer writes two methods: public void process(int a) { ... } and public void process(double a) { ... }. Which method is called by process(10)?

A.The method with double parameter
B.Compilation error: ambiguous call
C.The method with int parameter
D.Runtime error: NoSuchMethod
AnswerC

The int version is the best match for an int argument.

Why this answer

Option C is correct because Java selects the most specific overloaded method at compile time. When calling process(10), the integer literal 10 is an int, so the compiler prefers the method with the int parameter over the double parameter, as no implicit widening conversion is required.

Exam trap

Oracle often tests the misconception that Java will always widen an int to a double when both overloads exist, leading candidates to incorrectly choose the double parameter method.

How to eliminate wrong answers

Option A is wrong because Java does not automatically widen an int to a double when a more specific int overload exists; the compiler chooses the exact match. Option B is wrong because the call is not ambiguous; the int parameter method is a perfect match, so no ambiguity arises. Option D is wrong because the method with the int parameter exists and is accessible, so no runtime error occurs.

24
MCQeasy

Given the code snippet: 'int[] nums = {10, 20, 30, 40}; int sum = 0; for (int i = 0; i < nums.length; i++) { sum += nums[i]; }'. What is the value of sum after execution?

A.100
B.30
C.60
D.140
AnswerA

Sums all four elements correctly.

Why this answer

The correct answer is A (100) because the for loop iterates over each element of the array {10, 20, 30, 40} and adds it to the sum variable. The sum starts at 0, and after adding 10, 20, 30, and 40, the total becomes 100.

Exam trap

Oracle often tests whether candidates correctly compute the sum of all array elements versus partial sums, exploiting the common mistake of misinterpreting loop bounds or array indices.

How to eliminate wrong answers

Option B (30) is wrong because it represents only the sum of the first two elements (10 + 20) or a misunderstanding of the loop bounds. Option C (60) is wrong because it represents the sum of the first three elements (10 + 20 + 30) or a confusion with the array length. Option D (140) is wrong because it might result from incorrectly including an extra element or misreading the array values (e.g., adding 50 or double-counting).

25
MCQhard

A method 'public static void modify(int[][] matrix) { matrix[0][0] = 99; }' is called with 'int[][] values = {{1,2},{3,4}}; modify(values);'. What is the value of values[0][0] after the call?

A.99
B.Exception
C.1
D.0
AnswerA

The method modifies the original array element.

Why this answer

Option A is correct because Java passes object references by value. When 'modify(values)' is called, the reference to the 2D array is copied into the method parameter 'matrix'. Since 'matrix' points to the same array object, modifying 'matrix[0][0]' directly changes the original array's element, so 'values[0][0]' becomes 99.

Exam trap

The trap here is that candidates often confuse pass-by-value with pass-by-reference for objects, mistakenly thinking the method cannot modify the original array, or they assume an exception occurs due to incorrect array indexing.

How to eliminate wrong answers

Option B is wrong because no exception occurs; the method accesses a valid index (0,0) within the array bounds. Option C is wrong because the value 1 is overwritten by the assignment 'matrix[0][0] = 99', so it is not retained. Option D is wrong because 0 is the default value for uninitialized int array elements, but here the element was explicitly initialized to 1 and then changed to 99.

26
MCQhard

A programmer writes code to transpose a 2D array (matrix). Given: int[][] matrix = {{1,2},{3,4}}; int[][] result = new int[2][2]; for (int i=0; i<2; i++) for (int j=0; j<2; j++) result[j][i] = matrix[i][j]; What is the value of result[1][0]?

A.4
B.3
C.2
D.1
AnswerC

After transpose, result[1][0] equals original matrix[0][1].

Why this answer

The code transposes the matrix by assigning matrix[i][j] to result[j][i]. For result[1][0], we need the value where j=1 and i=0, which comes from matrix[0][1] = 2. Thus, result[1][0] = 2, making option C correct.

Exam trap

The trap here is confusing the indices: candidates often mistakenly think result[1][0] corresponds to matrix[1][0] (value 3) instead of correctly swapping to matrix[0][1] (value 2).

How to eliminate wrong answers

Option A is wrong because 4 would be the value of result[1][1] (from matrix[1][1]), not result[1][0]. Option B is wrong because 3 would be the value of result[0][1] (from matrix[1][0]), not result[1][0]. Option D is wrong because 1 would be the value of result[0][0] (from matrix[0][0]), not result[1][0].

27
MCQmedium

Consider a method that takes an int array and modifies it: public static void doubleArray(int[] arr) { for (int i = 0; i < arr.length; i++) { arr[i] *= 2; } }. What is the output of: int[] nums = {1, 2, 3}; doubleArray(nums); System.out.println(nums[1]);

A.4
B.8
C.2
D.3
AnswerA

The method doubles each element, so 2 becomes 4.

Why this answer

Option A is correct because the method `doubleArray` multiplies each element of the array by 2. The array `nums` is passed by reference, so modifications inside the method affect the original array. After execution, `nums[1]` (originally 2) becomes 4, which is printed.

Exam trap

The trap here is that candidates often confuse pass-by-value for object references with pass-by-value for primitives, incorrectly assuming the array is copied and the original remains unchanged, leading them to pick the original value (option C).

How to eliminate wrong answers

Option B is wrong because it assumes the entire array is doubled multiple times or that `nums[1]` becomes 8, which would require an extra doubling step. Option C is wrong because it represents the original value of `nums[1]` before the method call, ignoring that the array is modified in place. Option D is wrong because it suggests `nums[1]` remains 3, which is the value of `nums[2]` after doubling, not `nums[1]`.

28
MCQhard

A developer implements a method to check if a number exists in an array using binary search. The array is not sorted. What will happen?

A.The method returns correct results always.
B.Runtime exception.
C.Compilation error.
D.The method returns incorrect results sometimes.
AnswerD

Binary search may return incorrect results, such as not finding an existing element or returning a wrong index, because the array is not sorted.

Why this answer

Binary search requires the array to be sorted to work correctly. If the array is not sorted, the algorithm may skip over the target element or incorrectly conclude it is absent, leading to incorrect results. Therefore, the method returns incorrect results sometimes.

Exam trap

The trap here is that candidates assume binary search will still work or throw an error, but the exam tests the prerequisite that the array must be sorted for binary search to produce correct results.

How to eliminate wrong answers

Option A is wrong because binary search on an unsorted array does not guarantee correct results; it relies on the sorted order to eliminate halves. Option B is wrong because no runtime exception is thrown by the binary search logic itself; the code compiles and runs, but produces incorrect output. Option C is wrong because there is no compilation error; the method is syntactically valid and will compile successfully.

29
MCQeasy

Refer to the exhibit. What is the output?

A.3
B.2
C.1
D.0
AnswerB

result[0] = input[0]*2 = 1*2 = 2.

Why this answer

The code initializes an array `arr` with values {1, 2, 3}. The for loop iterates over the array, and the `if` condition checks if the current element equals 2. When `arr[1]` (value 2) is encountered, the `break` statement exits the loop immediately.

The loop executes only twice (for indices 0 and 1), so the counter `count` is incremented twice, resulting in output 2.

Exam trap

Oracle often tests the interaction between `break` and loop counters, where candidates mistakenly count all array elements or forget that `break` exits immediately without completing the remaining iterations.

How to eliminate wrong answers

Option A is wrong because it assumes the loop completes all three iterations and counts all elements, but the `break` exits early when value 2 is found. Option C is wrong because it suggests only one iteration occurs, but the loop runs for index 0 (value 1) and index 1 (value 2) before breaking, so count becomes 2. Option D is wrong because it implies the loop never executes or count is never incremented, but the loop does execute and increments count for each iteration before the break.

30
Multi-Selectmedium

Which two statements about the Arrays class are true? (Choose two.)

Select 2 answers
A.The Arrays class provides a method to sort only arrays of primitive types.
B.The Arrays class provides a method to fill an array with a specific value.
C.The Arrays class provides a method to perform binary search on any array.
D.The Arrays class provides a method to deep copy an array.
E.The Arrays class provides a method to convert an array to a List.
AnswersB, E

Arrays.fill() sets all elements to the specified value.

Why this answer

Option B is correct because the `Arrays.fill()` method allows you to assign a specific value to every element of an array, or to a specified range within the array. This is a static utility method provided by the `java.util.Arrays` class, and it works for both primitive and object arrays.

Exam trap

Cisco often tests the misconception that `Arrays.binarySearch()` works on any array, but it requires a sorted array; also, candidates may confuse `Arrays.copyOf()` with a deep copy, but it only performs a shallow copy.

31
MCQeasy

A banking application stores daily transaction amounts in an array. Which declaration correctly creates an array of 31 double values?

A.double[] transactions = new double[31];
B.double transactions[] = new double[30];
C.int[] transactions = new int[31];
D.double[] transactions = new double[];
AnswerA

Correct syntax: declares array and allocates 31 elements.

Why this answer

Option A is correct because it uses the proper syntax to declare an array of double values and initializes it with a size of 31, which allocates memory for 31 double elements, each defaulting to 0.0. In Java, the array size must be specified when using the 'new' keyword, and the index range is 0 to 30, accommodating exactly 31 daily transaction amounts.

Exam trap

Oracle often tests the distinction between array size and index range, tricking candidates into choosing an array of size 30 (index 0-29) when 31 elements are needed, or confusing the data type (int vs double) for monetary values.

How to eliminate wrong answers

Option B is wrong because it declares an array of 30 elements (size 30), not 31, which would not store all 31 daily transaction amounts. Option C is wrong because it declares an array of int values, not double values, so it cannot store fractional transaction amounts. Option D is wrong because it omits the array size in the initialization expression; in Java, 'new double[]' without a size is invalid syntax and will cause a compilation error.

32
MCQhard

A team is developing a financial application that processes large arrays of market data. They have a method that calculates moving averages by copying a subarray for each window. The current implementation creates a new array for each window using System.arraycopy. The application is running slowly in production. The team identifies that the method is called millions of times per minute. The array is large and the window size is small. The garbage collector overhead is high due to many short-lived arrays. Which optimization should they apply to reduce object creation and improve performance?

A.Use a Stream to process the array without creating intermediate arrays.
B.Use a single temporary array and reuse it by copying data into it for each window.
C.Use Arrays.copyOfRange() which is faster than System.arraycopy.
D.Use ArrayList instead of array to avoid copy.
AnswerB

Reuses one array, eliminating repeated allocations and reducing GC pressure.

Why this answer

Option B is correct because reusing a single temporary array eliminates the repeated allocation of short-lived arrays for each window, directly reducing garbage collector overhead. The current implementation uses System.arraycopy to create a new array per window, which is the primary source of object churn. By allocating one array once and copying data into it for each window, the team minimizes object creation while still performing the necessary copy operation.

Exam trap

Cisco often tests the misconception that using a more modern API (like Streams or copyOfRange) automatically improves performance, when in fact the key optimization is reducing object allocation frequency.

How to eliminate wrong answers

Option A is wrong because using a Stream does not inherently avoid intermediate array creation; streams may still allocate temporary objects or buffers, and the core issue of per-window array allocation is not addressed. Option C is wrong because Arrays.copyOfRange() internally creates a new array each time, so it does not reduce object creation; it may even be slower than System.arraycopy due to additional bounds checking. Option D is wrong because ArrayList internally uses an Object[] array and would still require copying or allocation for each window, and it introduces boxing overhead for primitive data types, worsening performance.

33
MCQeasy

A method is designed to compute the average of an array of test scores. What should the method return if the array is empty (length 0)?

A.Return 0.0
B.Do not compile; requires a return of type double
C.Throw a RuntimeException
D.Return null
AnswerA

Default value for empty average.

Why this answer

Option A is correct because the method should return 0.0 for an empty array to avoid division by zero and to provide a safe default value. In Java, an empty array has length 0, and computing the average would require dividing by zero, which throws an ArithmeticException. Returning 0.0 is a common convention for empty collections, as it allows the caller to handle the result gracefully without crashing.

Exam trap

Oracle often tests the distinction between primitive and wrapper types; the trap here is that candidates may think returning null is acceptable for a double return type, but double is a primitive and cannot hold null.

How to eliminate wrong answers

Option B is wrong because the code compiles fine; the method can return 0.0, which is a double literal, satisfying the return type. Option C is wrong because throwing a RuntimeException (like IllegalArgumentException) is not required by the language and would be poor design; the method should handle the edge case gracefully rather than forcing exception handling on the caller. Option D is wrong because null cannot be returned for a primitive double return type; the method signature specifies double, not Double, so null is not assignable.

34
Multi-Selecteasy

Which TWO statements are correct about array declaration and initialization in Java?

Select 2 answers
A.int[] a = new int[5];
B.int a[5];
C.int[] a = {1, 2, 3};
D.int a[5] = new int[5];
E.int[] a = new int[5] {1,2,3,4,5};
AnswersA, C

Valid declaration and allocation.

Why this answer

Option A is correct because `int[] a = new int[5];` declares an array of integers with a size of 5 and initializes all elements to their default value (0 for int). This is the standard syntax for array declaration and initialization in Java, where the size is specified after `new`.

Exam trap

Oracle often tests the distinction between C-style array syntax and Java's strict rules, specifically that you cannot combine a size specifier with an initializer list, and that size is never placed in the declaration brackets in Java.

35
MCQmedium

In a login system, the authentication method receives an array of user roles as a String[] and checks if a specific role is present. The array may be large (thousands of roles), and the method is called frequently for each user request. Performance is critical. The array is static and does not change after initialization. Which approach is most efficient for repeated checks?

A.Use a for loop to iterate and compare each string.
B.Sort the array and use Arrays.binarySearch().
C.Convert the array to a HashSet once and reuse it for lookups.
D.Use a List and the contains() method.
AnswerC

HashSet provides O(1) average lookup time.

Why this answer

Option C is correct because converting the array to a HashSet once provides O(1) average-time complexity for subsequent contains() checks, which is far more efficient than O(n) linear search or O(log n) binary search when the method is called frequently on a static array. The HashSet leverages hash codes for direct bucket lookup, making it ideal for repeated membership tests on large, unchanging data sets.

Exam trap

Oracle often tests the misconception that sorting and binary search is the most efficient approach for repeated lookups, but they overlook the upfront sorting cost and the fact that HashSet provides O(1) average-time complexity, which is superior for static, frequently queried data.

How to eliminate wrong answers

Option A is wrong because a for loop performs O(n) linear search on each call, which is inefficient for thousands of roles and frequent requests. Option B is wrong because sorting the array takes O(n log n) upfront, and binary search is O(log n) per check, but the overhead of sorting and the requirement for the array to remain sorted (which is unnecessary here) makes it less efficient than a HashSet for repeated lookups. Option D is wrong because List.contains() also performs O(n) linear search internally, offering no performance advantage over a simple for loop.

36
MCQhard

A developer needs to search an unsorted array of 100,000 customer IDs (int) for a specific ID. Which approach is most efficient for a single search?

A.Use Arrays.binarySearch() directly on the unsorted array
B.Iterate through the array and compare each element
C.First sort the array using Arrays.sort(), then use binary search
D.Convert the array to a HashSet and then search
AnswerB

Linear search has O(n) time, optimal for a single search on unsorted data.

Why this answer

Option B is correct because a linear search (iterating through the array and comparing each element) is the most efficient approach for a single search on an unsorted array. It has O(n) time complexity and requires no preprocessing, which is optimal when you only need to find one element once.

Exam trap

Oracle often tests the misconception that binary search is always faster, but candidates forget that binary search requires a sorted array and that sorting itself adds cost, making linear search more efficient for a single unsorted search.

How to eliminate wrong answers

Option A is wrong because Arrays.binarySearch() requires a sorted array; on an unsorted array, it produces undefined results (typically incorrect index or negative value). Option C is wrong because sorting the array first with Arrays.sort() (O(n log n)) and then performing binary search (O(log n)) is less efficient than a single linear scan (O(n)) for a one-time search. Option D is wrong because converting the array to a HashSet requires iterating through all elements (O(n)) and then searching (O(1) average), but the conversion overhead makes it less efficient than a simple linear search for a single query.

37
MCQmedium

A method 'public static double average(int[] numbers) { int sum = 0; for (int i = 0; i < numbers.length; i++) sum += numbers[i]; return sum / numbers.length; }' is called with array {10, 20, 30}. What change is needed to return the correct average?

A.Change the loop to for (int i = 1; i <= numbers.length; i++)
B.Change 'sum / numbers.length' to '(double) sum / numbers.length'
C.Change return type to int
D.Add a second parameter for the length
AnswerB

Ensures floating-point division.

Why this answer

The method performs integer division because both `sum` (int) and `numbers.length` (int) are integers, truncating the fractional part. Casting `sum` to `double` before division forces floating-point arithmetic, preserving the decimal value. For the array {10, 20, 30}, the correct average is 20.0, but integer division yields 20 (truncated from 20.0, though here it matches by coincidence; for non-integer averages like {10, 20, 31}, the error would be obvious).

Exam trap

Oracle often tests the distinction between integer and floating-point division in Java, trapping candidates who overlook that dividing two ints always truncates the decimal, even when assigned to a double variable or returned from a double method.

How to eliminate wrong answers

Option A is wrong because changing the loop to start at index 1 would skip the first element (10), and using `<=` would cause an ArrayIndexOutOfBoundsException when `i` equals `numbers.length`. Option C is wrong because changing the return type to int does not fix the integer division issue; the result would still be truncated, and the method signature would no longer match the intended return of a double average. Option D is wrong because the array already provides its length via `numbers.length`, and adding a second parameter is unnecessary and would not resolve the integer division problem.

38
Matchingmedium

Match each control flow statement to its purpose.

Drag a concept onto its matching description — or click a concept then click the description.

Concepts
Matches

Executes a block based on a boolean condition

Selects one of many code blocks based on a value

Iterates a fixed number of times

Repeats while a condition is true

Executes at least once then repeats while condition true

Why these pairings

Control flow statements manage the execution path.

39
Multi-Selecthard

Which THREE statements are correct about the 'main' method signature in Java?

Select 3 answers
A.It must be declared public.
B.It can be declared to return an int.
C.It must be declared void.
D.It must be declared static.
E.It can be named any valid identifier.
AnswersA, C, D

JVM needs access to call it.

Why this answer

Option A is correct because the Java Language Specification (JLS) requires the main method to be declared public so that the JVM can access it from outside the class. Without public visibility, the JVM would not be able to invoke the method as the entry point of the application.

Exam trap

Oracle often tests the misconception that the main method can have a non-void return type or a different name, tricking candidates who confuse it with other methods or C/C++ entry points.

40
MCQhard

A method is declared as: public static int[] generateSequence(int n) { ... }. Which return statement is valid inside this method?

A.return result; where result is an int variable
B.return new int[n];
C.return 0;
D.return new int[0];
AnswerB

Creates and returns an int array of size n.

Why this answer

Option C is correct because the return type is int[], and new int[n] creates an array of ints, which matches. Option A returns a primitive int, not an array. Option B returns a reference to an int array, but the assignment is wrong because the method returns a reference; the local variable is unnecessary but valid if assigned.

Actually, 'return new int[n]' is correct; 'int[] result = new int[n]; return result;' is also correct. But among options, C is clearly correct. Option D returns an empty array but that is also valid, but C is more typical.

Need to choose one best. Let's refine: Option C is correct because it directly creates and returns an int array. Option D is also correct but the question asks for a valid statement; both would be valid.

To make a single correct, we can say only C is presented as correct. Actually let me adjust options so only one is fully correct.

41
MCQmedium

A developer writes a method that accepts an array and returns the sum of all elements. Which implementation is correct if the array might be null?

A.public int sum(int[] arr) { if (arr.length==0) return 0; int s=0; for (int n:arr) s+=n; return s; }
B.public int sum(int[] arr) { if (arr == null) return 0; int s=0; for (int n:arr) s+=n; return s; }
C.public int sum(int[] arr) { try { int s=0; for (int n:arr) s+=n; return s; } catch(NullPointerException e) { return -1; } }
D.public int sum(int[] arr) { int s=0; for (int n:arr) s+=n; return s; }
AnswerB

Correctly handles null and empty arrays.

Why this answer

Option A is best practice because it handles null gracefully by returning 0. B throws NullPointerException if null. C checks length but not null.

D uses exception handling for flow control which is not recommended.

42
MCQeasy

A method is designed to reverse an array of integers. The method signature is: public static void reverse(int[] arr). The method correctly reverses the array. Which statement is true about the method?

A.It modifies the original array.
B.It returns a new array that is the reverse of the input.
C.It cannot be called with a null array.
D.It uses pass-by-value, so the original array is unchanged.
AnswerA

Since it returns void, the only way to provide the reversed array to the caller is by modifying the input array.

Why this answer

Option A is correct because the method receives a reference to the array (pass-by-value of the reference), so any modifications made to the array elements inside the method directly affect the original array object in the caller's scope. Since the method reverses the array in-place by swapping elements, the original array is mutated.

Exam trap

Oracle often tests the misconception that Java uses pass-by-reference for objects; the trap here is that candidates think 'pass-by-value' means the original array cannot be changed, but in reality, the reference is passed by value, allowing mutation of the array's contents.

How to eliminate wrong answers

Option B is wrong because the method has a void return type, so it cannot return a new array; it reverses the array in-place. Option C is wrong because the method can be called with a null array; it would simply throw a NullPointerException at runtime, but the statement says 'it cannot be called' which is false — it can be called, though it will fail. Option D is wrong because Java uses pass-by-value for references, meaning the reference value is copied, but the object (the array) is shared; modifications to the array's elements are visible to the caller, so the original array is changed.

43
MCQeasy

A new developer writes a method that accepts an array and intends to swap the first and last elements. The code is: public static void swapEnds(int[] arr) { int temp = arr[0]; arr[0] = arr[arr.length-1]; arr[arr.length-1] = temp; } What is a potential issue with this method if the array is empty?

A.It will throw a NullPointerException.
B.It will throw an ArrayIndexOutOfBoundsException.
C.It will produce incorrect result because arr.length-1 is negative.
D.It will compile and run correctly.
AnswerB

Accessing index 0 and -1 on an empty array throws this exception.

Why this answer

When the array is empty, `arr.length` is 0, so `arr.length - 1` evaluates to -1. Accessing `arr[-1]` throws an `ArrayIndexOutOfBoundsException` because array indices must be non-negative and less than the array length. The method does not check for an empty array before attempting the swap.

Exam trap

Oracle often tests the distinction between a `null` reference and an empty array, leading candidates to mistakenly think an empty array causes a `NullPointerException` instead of an `ArrayIndexOutOfBoundsException`.

How to eliminate wrong answers

Option A is wrong because a `NullPointerException` occurs only when the array reference itself is `null`, not when the array is empty. Option C is wrong because the method does not produce an incorrect result; it throws an exception before any result can be produced. Option D is wrong because the method does not compile and run correctly for an empty array; it throws an `ArrayIndexOutOfBoundsException` at runtime.

44
MCQeasy

A method is declared as 'public void printElements(int... numbers)'. Which invocation will cause a compilation error?

A.printElements({1,2,3});
B.printElements(1, 2, 3);
C.printElements();
D.printElements(new int[]{1,2,3});
AnswerA

Invalid syntax; must be new int[]{1,2,3}.

Why this answer

Option A is correct because the syntax `{1,2,3}` is an array initializer that can only be used in a variable declaration or as part of an array creation expression (e.g., `new int[]{1,2,3}`). It cannot be passed directly as an argument to a varargs method. The varargs parameter `int... numbers` expects either a sequence of `int` values or an `int[]` array reference, but not an anonymous array initializer.

Exam trap

The trap here is that candidates mistakenly think an array initializer like `{1,2,3}` can be used anywhere an array is expected, but in Java it is only valid in declarations or with `new` — not as a standalone method argument.

How to eliminate wrong answers

Option B is wrong because `printElements(1, 2, 3)` is a valid invocation — the varargs parameter `int... numbers` automatically packs the three arguments into an array. Option C is wrong because `printElements()` is a valid invocation — varargs allows zero arguments, resulting in an empty array. Option D is wrong because `printElements(new int[]{1,2,3})` is a valid invocation — an explicit array creation expression can be passed directly to a varargs parameter.

45
MCQhard

A method 'public static void modifyArray(int[] arr) { arr[0] = 99; }' is called with 'int[] myArray = {1,2,3}; modifyArray(myArray); System.out.println(myArray[0]);'. What is the output?

A.99
B.1
C.0
D.Compilation error
AnswerA

The method modifies the array element.

Why this answer

In Java, when an array is passed to a method, the reference to the array is passed by value. This means the method receives a copy of the reference, but both the original and the copy point to the same array object in heap memory. Therefore, modifying an element of the array inside the method (arr[0] = 99) directly changes the original array's content.

When myArray[0] is printed after the call, it outputs 99.

Exam trap

Oracle often tests the misconception that Java passes objects by value in the sense that the object itself is copied, leading candidates to incorrectly think that changes inside a method do not affect the original array.

How to eliminate wrong answers

Option B is wrong because it assumes that the array is passed by value in the sense that the entire array is copied, which is not true for objects in Java; only the reference is copied, so changes to array elements affect the original. Option C is wrong because it suggests that the array element is initialized to 0 by default, but myArray is explicitly initialized with {1,2,3}, so arr[0] is 1 before modification. Option D is wrong because the code compiles and runs without error; the method signature matches the call, and the array is a valid argument.

46
MCQeasy

A developer is writing a method to compute the average of an array of scores. The method should handle edge cases gracefully. The scores array may be empty or contain null values if the collection was interrupted. The scores are stored as primitive doubles. Which implementation is safest and follows best practices?

A.public double average(double[] scores) { if (scores == null || scores.length == 0) return 0.0; double sum = 0; for (double s : scores) sum += s; return sum / scores.length; }
B.public double average(double[] scores) { double sum = 0; for (double s : scores) sum += s; return sum / scores.length; }
C.public double average(double[] scores) { try { double sum = 0; for (double s : scores) sum += s; return sum / scores.length; } catch (NullPointerException | ArithmeticException e) { return 0.0; } }
D.public double average(double[] scores) { if (scores == null) return 0.0; double sum = 0; for (double s : scores) sum += s; return scores.length == 0 ? 0.0 : sum / scores.length; }
AnswerD

Explicitly avoids division by zero and handles null.

Why this answer

Option D is correct because it explicitly checks for both a null array and an empty array before performing the division. The null check prevents a NullPointerException, and the ternary operator `scores.length == 0 ? 0.0 : sum / scores.length` avoids division by zero when the array is empty. This follows best practices by handling edge cases without relying on exceptions for flow control.

Exam trap

The trap here is that candidates may think catching NullPointerException or using a single check for null is sufficient, but they overlook that an empty array requires a separate check to avoid division by zero, and that double division by zero does not throw an exception.

How to eliminate wrong answers

Option A is wrong because it returns 0.0 for an empty array, but the problem states scores are stored as primitive doubles (not Double objects), so null values in the array are impossible; however, the main flaw is that it does not check for null array, which would cause a NullPointerException if scores is null. Option B is wrong because it lacks any null or empty check, so it will throw a NullPointerException if scores is null and an ArithmeticException (division by zero) if scores.length is 0. Option C is wrong because it uses exception handling for flow control, which is poor practice; also, ArithmeticException is never thrown for double division by zero (it yields Infinity or NaN), so the catch block would not handle the empty array case correctly.

47
MCQmedium

Refer to the exhibit. Which overloaded methods cause this compilation error?

A.public void print(String s) and public void print(String[] s)
B.public void print(String s) and public void print(String... s)
C.public void print(String[] s) and public void print(String... s)
D.public void print(Object... o) and public void print(String... s)
AnswerC

Both match when passing null, causing ambiguity.

Why this answer

Option C is correct because Java does not allow overloading methods that differ only by the use of a varargs parameter and an array parameter of the same type. Both `public void print(String[] s)` and `public void print(String... s)` have the same method signature after erasure — they both accept a `String[]` at the bytecode level — causing a compilation error due to ambiguity.

Exam trap

The trap here is that candidates mistakenly think varargs and arrays are distinct types for overloading, but Java treats them identically after compilation, so defining both `print(String[])` and `print(String...)` causes a duplicate method error.

How to eliminate wrong answers

Option A is wrong because `public void print(String s)` and `public void print(String[] s)` have different parameter types (a single String vs. an array of String), which is a valid overload. Option B is wrong because `public void print(String s)` and `public void print(String... s)` are valid overloads; the compiler can distinguish between a single String argument and a varargs call. Option D is wrong because `public void print(Object... o)` and `public void print(String... s)` have different parameter types (Object varargs vs.

String varargs), so they are valid overloads and do not cause a compilation error.

48
MCQmedium

A team is developing a Java application for an online store. The application has a class 'Inventory' that maintains an array of 'Product' objects. The method 'public void addProduct(Product p)' is intended to add a product to the array. The current implementation uses a fixed-size array of length 100. However, the business has grown, and the array may exceed its capacity. The team needs a solution that allows dynamic resizing without changing the method signature. Which approach should the team take?

A.Modify the method to use an ArrayList<Product> internally and keep the signature.
B.Change the method signature to accept a Product[] array and copy all elements.
C.Use a Collection<Product> as parameter and convert to array.
D.Change the return type to boolean and return false if array is full.
AnswerA

Allows dynamic resizing with same signature.

Why this answer

Option A is correct because using an ArrayList<Product> internally allows the array to dynamically resize as needed, while keeping the method signature unchanged. The method still accepts a Product parameter, but the internal implementation leverages ArrayList's automatic capacity management, eliminating the fixed-size constraint.

Exam trap

The trap here is that candidates may think changing the return type or parameter type is acceptable, but the question explicitly requires keeping the method signature unchanged, so only internal implementation changes are allowed.

How to eliminate wrong answers

Option B is wrong because changing the method signature to accept a Product[] array violates the requirement to keep the signature unchanged. Option C is wrong because using a Collection<Product> as a parameter also changes the method signature, which is not allowed. Option D is wrong because changing the return type to boolean and returning false when the array is full does not solve the capacity issue; it merely reports failure without enabling dynamic resizing.

49
MCQmedium

A developer writes a method that takes an int array and returns the sum of its elements. The method signature is: 'public static int sumArray(int[] arr)'. Which statement correctly calls this method?

A.int result = sumArray(new int[]{1,2,3});
B.int result = sumArray(true);
C.int result = sumArray([1,2,3]);
D.int result = sumArray(5);
AnswerA

Creates and passes an anonymous int array.

Why this answer

Option A is correct because it uses the correct syntax for creating and passing an anonymous int array to the sumArray method. The expression `new int[]{1,2,3}` creates an int array object with the specified elements, which matches the method's parameter type `int[]`. The method then returns the sum, which is assigned to the int variable `result`.

Exam trap

Oracle often tests the distinction between array initializer syntax (valid only in declarations) and anonymous array syntax (required when passing an array directly to a method), causing candidates to mistakenly use `[1,2,3]` or a single value instead of the proper `new int[]{...}` form.

How to eliminate wrong answers

Option B is wrong because it passes a boolean value `true` to a method that expects an `int[]` parameter, causing a compilation error due to type mismatch. Option C is wrong because `[1,2,3]` is not valid Java syntax for an array literal; Java requires either `new int[]{1,2,3}` or `{1,2,3}` only in variable declarations. Option D is wrong because it passes a single integer `5` instead of an int array, which does not match the method's parameter type and will cause a compilation error.

50
Multi-Selectmedium

Which TWO statements are true about passing arrays to methods in Java?

Select 2 answers
A.The method can reassign the original array variable to a new array.
B.The method can modify the elements of the array.
C.The method must return the array to reflect any changes.
D.The method receives a copy of the array reference.
E.The method cannot determine the size of the array.
AnswersB, D

Changes to array elements affect the original array.

Why this answer

Option B is correct because Java passes object references by value. When an array is passed to a method, the method receives a copy of the reference to the array object. This copy still points to the same array object in heap memory, so the method can modify the elements of the array through that reference.

These modifications are visible to the caller because they affect the same underlying array object.

Exam trap

The trap here is that candidates often confuse 'pass by reference' with 'pass by value of the reference,' leading them to incorrectly believe that reassigning the parameter inside the method will affect the caller's variable (Option A), or that modifications to array elements require a return value (Option C).

51
Multi-Selecthard

Which two statements about method parameter passing in Java are true? (Choose two.)

Select 2 answers
A.When an array is passed to a method, changes to the array elements inside the method are not reflected in the caller.
B.When an array is reassigned inside a method, the original array in the caller is also reassigned.
C.When a primitive type is passed to a method, a copy of the value is passed.
D.When an object is passed to a method, a reference to the object is passed by value.
E.When a String is passed to a method, the method can modify the original String.
AnswersC, D

Primitives are pass-by-value, so the original variable is not modified.

Why this answer

Option C is correct because Java always passes primitive types (like int, double, boolean) by value, meaning a copy of the actual value is made and passed into the method. Any modifications to the parameter inside the method affect only the copy, not the original variable in the caller.

Exam trap

The trap here is that candidates often confuse 'pass-by-reference' with 'pass-by-value of a reference,' leading them to incorrectly believe that reassigning an object parameter inside a method affects the caller's reference, or that primitive types are passed by reference.

52
MCQmedium

Which method invocation is ambiguous given these overloaded methods? public void process(int[] a) and public void process(int... a)

A.process(1, 2);
B.process((int[]) null);
C.process();
D.process(new int[]{1, 2});
AnswerD

Both methods accept an int array, causing ambiguity.

Why this answer

Option D is correct because when you call process(new int[]{1, 2}), the compiler cannot determine whether to use the method with an int[] parameter or the varargs method (int... a). Both methods have the same signature after type erasure, and the argument is an int array, which matches both exactly, causing an ambiguity error.

Exam trap

The trap here is that candidates think varargs and array parameters are distinct, but they are not; the compiler treats them as identical when the argument is an array, leading to ambiguity.

How to eliminate wrong answers

Option A is wrong because process(1, 2) passes two int arguments, which unambiguously matches the varargs method (int... a) since the array method requires a single int[] argument. Option B is wrong because process((int[]) null) explicitly casts null to int[], which unambiguously matches the array method (int[] a) and not the varargs method. Option C is wrong because process() with no arguments unambiguously matches the varargs method (int... a) with an empty array, and does not match the array method which requires an int[] argument.

53
MCQmedium

A method 'public static int findMax(int[] numbers)' returns the maximum value in the array. Which implementation correctly handles an empty array by returning 0?

A.int max = 0; for(int n: numbers) if(n > max) max = n; return max;
B.int max = numbers[0]; for(int i=1; i<numbers.length; i++) if(numbers[i] > max) max = numbers[i]; return max;
C.if(numbers.length == 0) return 0; int max = 0; for(int n: numbers) if(n > max) max = n; return max;
D.if(numbers.length == 0) return 0; int max = numbers[0]; for(int i=1; i<numbers.length; i++) if(numbers[i] > max) max = numbers[i]; return max;
AnswerD

Correctly handles empty and non-empty arrays.

Why this answer

Option D correctly handles an empty array by checking `numbers.length == 0` and returning 0 before attempting to access `numbers[0]`, which would throw an `ArrayIndexOutOfBoundsException` on an empty array. It then initializes `max` to the first element and iterates from index 1, ensuring all elements are compared correctly even if all numbers are negative.

Exam trap

The trap here is that candidates often choose Option C because they see the empty check but overlook that initializing `max` to 0 instead of the first element causes incorrect results for arrays with all negative numbers, which Cisco frequently uses to test understanding of edge cases and initialization logic.

How to eliminate wrong answers

Option A is wrong because it initializes `max = 0`, which fails if all array elements are negative (returns 0 instead of the actual maximum negative value) and does not handle an empty array (returns 0 but without explicit check, which is acceptable only if the spec requires returning 0 for empty arrays, but the lack of check is a design flaw). Option B is wrong because it accesses `numbers[0]` without checking if the array is empty, causing an `ArrayIndexOutOfBoundsException` at runtime. Option C is wrong because it initializes `max = 0` after the empty check, so it still fails for arrays with all negative numbers (returns 0 instead of the correct negative maximum).

54
MCQmedium

Consider the following code: int[] arr = new int[5]; for (int i = 0; i <= arr.length; i++) { arr[i] = i; } System.out.println(arr[0]); What is the result?

A.0
B.5
C.4
D.An ArrayIndexOutOfBoundsException is thrown.
AnswerD

The loop runs i from 0 to 5 inclusive; when i equals 5, arr[5] is out of bounds, causing the exception.

Why this answer

The correct answer is D because the loop condition `i <= arr.length` causes `i` to iterate from 0 to 5 inclusive. Since `arr` has indices 0 through 4, accessing `arr[5]` throws an `ArrayIndexOutOfBoundsException`. The exception occurs before `arr[0]` can be printed.

Exam trap

The trap here is that candidates often overlook the off-by-one error in the loop condition `i <= arr.length` and assume the loop runs correctly, forgetting that array indices start at 0 and end at `length - 1`.

How to eliminate wrong answers

Option A is wrong because although `arr[0]` would be assigned 0 if the loop completed, the exception halts execution before the print statement. Option B is wrong because `arr.length` is 5, but the loop never assigns 5 to any element; the exception prevents any output. Option C is wrong because 4 is the last valid index, but the loop attempts to access index 5, causing an exception.

55
MCQmedium

Given the method: public static void modify(int[] data) { data = new int[]{10,20}; } What is the output of: int[] vals = {1,2}; modify(vals); System.out.println(vals[0]);

A.10
B.Compilation error
C.1
D.0
AnswerC

Correct: the original array is unchanged.

Why this answer

In Java, when an object reference (including an array) is passed to a method, the reference itself is passed by value. Inside `modify`, the assignment `data = new int[]{10,20}` reassigns the local variable `data` to a new array object, but this does not affect the original reference `vals` in the caller. Therefore, `vals[0]` remains `1`, making option C correct.

Exam trap

The trap here is that candidates often confuse reassigning a reference with modifying the object's contents, leading them to incorrectly believe the original array is replaced.

How to eliminate wrong answers

Option A is wrong because it assumes the method modifies the original array, but the assignment `data = new int[]{10,20}` only changes the local reference, not the caller's array. Option B is wrong because the code compiles successfully; the method signature matches the call, and no syntax or type errors exist. Option D is wrong because it suggests the array element becomes 0, which would only happen if the original array were modified to contain 0, but no such modification occurs.

56
MCQmedium

What is printed when the main method runs?

A.5
B.0
C.Compilation error: cannot assign new array to parameter
D.100
AnswerA

The original array is not modified; the method reassigned the reference.

Why this answer

Option A is correct because the method `modifyArray` receives a reference to the array, and the assignment `arr = new int[]{100};` changes the local reference `arr` to point to a new array object. The original array in `main` remains unchanged, so `arr[0]` still prints 5. Java passes object references by value, meaning the reference itself is copied, and reassigning the local reference does not affect the caller's reference.

Exam trap

Oracle often tests the distinction between modifying an object's state (which affects the caller) versus reassigning the reference (which does not), and the trap here is that candidates mistakenly think reassigning the parameter changes the original array, leading them to choose option D.

How to eliminate wrong answers

Option B is wrong because the array is initialized with `{5}` and never modified in the calling scope, so `arr[0]` is 5, not 0. Option C is wrong because there is no compilation error; Java allows reassigning a method parameter (the local reference) to a new array, as the parameter is a local variable. Option D is wrong because the new array `{100}` is only assigned to the local reference inside `modifyArray` and does not affect the original array in `main`, so `arr[0]` remains 5, not 100.

57
MCQeasy

A method that calculates the average of an array of doubles is defined as: public static double average(double[] values) { double sum = 0; for (double v : values) sum += v; return sum / values.length; } Which call is valid?

A.double avg = average(1.0, 2.0);
B.double avg = average(new double[]{1.0, 2.0, 3.0});
C.double avg = average(1.0, 2.0, 3.0);
D.double avg = average({1.0, 2.0, 3.0});
AnswerB

This creates a double array and passes it to the method.

Why this answer

Option B is correct because the method `average(double[] values)` expects a single argument of type `double[]`. The expression `new double[]{1.0, 2.0, 3.0}` creates an anonymous array object that matches the parameter type exactly, so the call compiles and runs correctly.

Exam trap

Oracle often tests the difference between array initializer syntax and anonymous array creation, trapping candidates who think `{1.0, 2.0, 3.0}` can be used as a method argument without the `new double[]` prefix.

How to eliminate wrong answers

Option A is wrong because the method expects a single `double[]` argument, but `1.0, 2.0` are two separate `double` literals, not an array; Java does not support implicit array creation from a comma-separated list in a method call. Option C is wrong for the same reason: three separate `double` literals cannot be passed to a parameter that expects a single `double[]` reference. Option D is wrong because `{1.0, 2.0, 3.0}` is an array initializer syntax that is only valid in a declaration (e.g., `double[] arr = {1.0, 2.0, 3.0};`), not as a standalone expression in a method call.

58
MCQhard

A developer wants to sort an array of primitive ints in descending order. Which approach will work without using third-party libraries?

A.Arrays.parallelSort(arr);
B.Arrays.sort(arr, Collections.reverseOrder());
C.Arrays.sort(arr); // then reverse the array manually
D.Arrays.sort(arr, (a,b) -> b - a);
AnswerC

Sorts ascending, then reversing yields descending order.

Why this answer

Option C is correct because `Arrays.sort(int[])` sorts the array in ascending order, and then manually reversing the array yields descending order. The other options fail because `Arrays.parallelSort()` also sorts ascending, `Collections.reverseOrder()` requires an array of objects (not primitives), and a custom comparator cannot be used with primitive arrays in Java.

Exam trap

The trap here is that candidates assume `Arrays.sort()` with a comparator works on primitive arrays, but Java's type system prevents this because comparators require object types, leading to a compilation error for `int[]`.

How to eliminate wrong answers

Option A is wrong because `Arrays.parallelSort(int[])` sorts the array in ascending order, not descending. Option B is wrong because `Collections.reverseOrder()` returns a `Comparator<T>` that works only with object arrays (e.g., `Integer[]`), not with primitive `int[]` arrays. Option D is wrong because `Arrays.sort()` for primitive arrays does not accept a `Comparator`; the overload that accepts a comparator works only with object arrays, and using a lambda with primitive arrays causes a compilation error.

59
MCQeasy

What is the result of the following code? int[] arr = new int[3]; arr[3] = 5; System.out.println(arr[3]);

A.Runtime exception
B.0
C.5
D.Compilation error
AnswerA

ArrayIndexOutOfBoundsException is thrown at runtime.

Why this answer

The code attempts to access index 3 of an array of length 3. Since Java arrays are zero-indexed, valid indices are 0, 1, and 2. Accessing index 3 throws an ArrayIndexOutOfBoundsException at runtime, so option A is correct.

Exam trap

Oracle often tests the distinction between compile-time errors and runtime exceptions, and the trap here is that candidates mistakenly think an invalid array index causes a compilation error, when in fact the compiler only checks syntax and type safety, not index bounds.

How to eliminate wrong answers

Option B is wrong because it suggests the output is 0, but the array element at index 3 was never assigned and the exception prevents any output. Option C is wrong because it assumes the assignment succeeds, but the index is out of bounds, so the assignment never executes. Option D is wrong because the code compiles successfully; the error occurs only at runtime when the invalid index is accessed.

60
MCQmedium

A developer writes a method that takes a variable number of integer arguments and returns the maximum. Which method signature is correct?

A.public int max(int[]... numbers)
B.public int max(int... numbers)
C.public int max(int numbers)
D.public int max(int[] numbers)
AnswerB

Varargs allows zero or more arguments, and inside the method it is treated as an array of int.

Why this answer

Option B is correct because the varargs syntax `int... numbers` allows a method to accept zero or more integer arguments, which are then treated as an array inside the method. This is the standard Java syntax for variable-length argument lists, enabling the developer to pass any number of `int` values and compute the maximum.

Exam trap

Oracle often tests the distinction between varargs (`int...`) and array parameters (`int[]`), trapping candidates who think they are interchangeable without understanding that varargs allows passing individual values directly while an array parameter requires explicit array creation.

How to eliminate wrong answers

Option A is wrong because `int[]... numbers` declares a varargs of `int[]` arrays, meaning it expects an array of integer arrays, not a variable number of individual `int` values. Option C is wrong because `int numbers` is a single integer parameter, which cannot accept multiple arguments. Option D is wrong because `int[] numbers` accepts a single integer array parameter, not a variable number of individual `int` arguments.

61
MCQhard

Which of the following correctly describes the effect of the method call 'Arrays.sort(myArray)' on an array of objects that do not implement Comparable?

A.The code does not compile because Arrays.sort requires a Comparator.
B.A ClassCastException is thrown at runtime.
C.The array is sorted using the natural order of the elements.
D.The array is sorted using the order defined by the elements' equals method.
AnswerB

Elements must implement Comparable.

Why this answer

When `Arrays.sort(myArray)` is called on an array of objects that do not implement the `Comparable` interface, the method attempts to cast elements to `Comparable` to compare them. Since the objects do not implement `Comparable`, a `ClassCastException` is thrown at runtime. The `Arrays.sort(Object[])` method requires that all elements implement `Comparable`; otherwise, it cannot determine a natural ordering.

Exam trap

The trap here is that candidates assume the code will not compile (Option A) because they think `Comparable` is required at compile time, but the requirement is enforced at runtime via a cast, leading to a `ClassCastException`.

How to eliminate wrong answers

Option A is wrong because `Arrays.sort(Object[])` does not require a `Comparator`; it uses the natural ordering defined by `Comparable`. Option C is wrong because the array cannot be sorted using natural order if the elements do not implement `Comparable`; the method will throw an exception instead. Option D is wrong because `Arrays.sort` does not use the `equals` method for ordering; it uses `compareTo` (from `Comparable`) or a provided `Comparator`.

62
Multi-Selecthard

Which two statements about passing arrays to methods are correct? (Select two.)

Select 2 answers
A.Passing an array is the same as passing each element individually.
B.The method can change the size of the original array.
C.Modifying the array elements inside the method affects the original array.
D.If the method assigns a new array to the parameter, the original reference is updated outside the method.
E.The array reference is passed by value.
AnswersC, E

Since the method has a reference to the same array object, changes to elements are visible to the caller.

Why this answer

Options A and B are correct. The array reference is passed by value (A), so modifications to the array elements affect the original (B). Option C is false because passing an array is not the same as passing elements individually.

Option D is false because the array size is fixed. Option E is false because assigning a new array to the parameter does not affect the caller's reference.

63
MCQhard

Given 'int[] source = {1,2,3,4,5};' and 'int[] dest = new int[3];' which code correctly copies the first three elements from source to dest using System.arraycopy?

A.System.arraycopy(source, 0, dest, 0, 3);
B.System.arraycopy(source, 0, dest, 0, 5);
C.System.arraycopy(source, 1, dest, 0, 3);
D.System.arraycopy(source, 0, dest, 1, 3);
AnswerA

Correct parameters.

Why this answer

Option A is correct because `System.arraycopy(source, 0, dest, 0, 3)` copies exactly three elements starting from index 0 of the source array to index 0 of the destination array, matching the requirement. The `length` argument (3) specifies the number of array elements to copy, and the destination array has a capacity of 3, so no `ArrayIndexOutOfBoundsException` occurs.

Exam trap

Oracle often tests the misconception that the `length` parameter refers to the total size of the destination array rather than the number of elements to copy, leading candidates to choose option B.

How to eliminate wrong answers

Option B is wrong because `length` is 5, which would attempt to copy 5 elements into `dest` that only has 3 elements, causing an `ArrayIndexOutOfBoundsException`. Option C is wrong because `srcPos` is 1, so it copies elements starting from index 1 (values 2,3,4) instead of the first three elements (1,2,3). Option D is wrong because `destPos` is 1, so it would place the copied elements starting at index 1 of `dest`, leaving index 0 unchanged and potentially causing an `ArrayIndexOutOfBoundsException` when writing beyond the array bounds.

64
MCQeasy

Which of the following correctly declares and initializes an array of strings with the elements "A", "B", and "C"?

A.String[] arr = new String[] {"A", "B", "C"};
B.String[] arr = ("A", "B", "C");
C.String[] arr = ["A", "B", "C"];
D.String[] arr = {"A", "B", "C"};
AnswerD

Correct shorthand initialization.

Why this answer

Option D is correct because in Java, an array can be declared and initialized using the array initializer syntax with curly braces `{}` directly after the declaration, as in `String[] arr = {"A", "B", "C"};`. This is a shorthand that implicitly creates a new array object with the specified elements, and it is only valid in a declaration statement (not in an assignment to an already-declared variable).

Exam trap

Oracle often tests the distinction between the shorthand array initializer (using curly braces) and the anonymous array creation expression (using `new`), and the trap here is that candidates may incorrectly choose the `new` syntax (Option A) because it is also valid, but the exam expects the most direct and standard declaration form without the `new` keyword.

How to eliminate wrong answers

Option A is wrong because `String[] arr = new String[] {"A", "B", "C"};` is syntactically valid but it uses an anonymous array creation expression with an explicit `new` keyword, which is not the simplest or most direct way to declare and initialize in one line; however, the question asks for the correct declaration and initialization, and while this syntax works, it is not the standard shorthand that the exam expects (the exam considers the array initializer without `new` as the correct form for this context). Option B is wrong because `String[] arr = ("A", "B", "C");` uses parentheses, which is invalid syntax in Java for array initialization; parentheses are used for grouping expressions or method calls, not for array literals. Option C is wrong because `String[] arr = ["A", "B", "C"];` uses square brackets, which is invalid syntax in Java for array initialization; square brackets are used for array indexing or type declaration, not for defining array contents.

65
Drag & Dropmedium

Arrange the steps to create an object from a class in Java in the correct order.

Drag steps to the numbered slots on the right, or tap a step then tap a slot.

Steps
Order

Why this order

First define the class, then declare a variable, instantiate with new, assign to variable, and then use the object.

66
Multi-Selecthard

Which THREE statements are true about method overloading in Java?

Select 3 answers
A.Two methods with the same name, same parameter types, but different return types are overloaded.
B.The return type can be different, but it is not sufficient to differentiate overloaded methods.
C.Method overloading is resolved at runtime.
D.Overloaded methods can be defined in the same class.
E.Overloaded methods must have different parameter lists.
AnswersB, D, E

Return type alone does not distinguish overloads.

Why this answer

Option B is correct because in Java, method overloading requires methods to have different parameter lists. While the return type can be different, it alone is not sufficient to differentiate overloaded methods; the compiler uses the method signature (name + parameter types) to resolve overloads, and return type is not part of the signature.

Exam trap

The trap here is that candidates often confuse overloading with overriding, mistakenly thinking that return type or runtime resolution plays a role in overloading, when in fact overloading is purely compile-time and based on parameter lists.

67
MCQmedium

An application requires storing a fixed set of 12 monthly temperatures. Which initialization is most appropriate?

A.ArrayList<Double> temps = new ArrayList<>();
B.double[] temps = new double[12];
C.double[] temps = {15.5, 16.2, 18.0, 20.1, 23.4, 27.8, 30.0, 29.5, 26.2, 22.0, 18.5, 16.0};
D.double temps[] = {0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0};
AnswerC

Directly initializes with the needed values.

Why this answer

Option C is correct because it initializes a fixed-size array of 12 doubles with the actual monthly temperature values in a single statement, which is the most appropriate for storing a fixed set of 12 values. The array size is implicitly determined by the number of elements in the initializer list, and the syntax is concise and readable for this use case.

Exam trap

Oracle often tests the distinction between array declaration with an initializer list versus just allocating an array with default values, and the trap here is that candidates may choose Option B because it specifies the correct size, but overlook that it does not actually store the required temperature data.

How to eliminate wrong answers

Option A is wrong because ArrayList<Double> is a resizable collection, which is unnecessary and less efficient for a fixed set of 12 values; it also requires autoboxing for primitive doubles, adding overhead. Option B is wrong because it only declares an array of size 12 with default values (0.0), but does not initialize it with the actual temperature data, so it is incomplete for the requirement of storing the fixed set of monthly temperatures. Option D is wrong because it initializes all 12 elements to 0.0, which does not represent the actual monthly temperatures and is not the most appropriate initialization for the given data.

68
MCQhard

A company's legacy code has a method that takes an array of integers and returns a new array containing only the positive numbers. The current implementation uses a fixed-size array equal to the input size and counts positive numbers, then copies them, but if many negatives exist, the result array has trailing zeros (which are removed by copying again). This wastes memory and time. The array can be large (up to 1 million elements). The developer wants to improve memory efficiency and runtime without using external libraries. Which approach should they implement?

A.Use an ArrayList to collect positive numbers, then convert to int[].
B.Use a stream to filter and collect to array.
C.First count positives, then create an array of that exact size, fill it.
D.Use a linked list and then convert.
AnswerC

Efficient: exactly allocated array, O(n) time.

Why this answer

Option C is correct because it avoids the overhead of dynamic resizing (as in ArrayList) or boxing (as in streams) by first counting the positives in a single pass, then creating an exact-sized int[] array, and filling it in a second pass. This yields O(n) time complexity and minimal memory overhead, directly addressing the legacy code's inefficiency without external libraries.

Exam trap

Oracle often tests the misconception that ArrayList or streams are always more efficient, but here the constraint 'without using external libraries' and the need for primitive efficiency make the two-pass counting approach the correct choice.

How to eliminate wrong answers

Option A is wrong because ArrayList<Integer> requires autoboxing each int to Integer, consuming more memory and CPU, and its internal array may need resizing, adding overhead. Option B is wrong because streams involve boxing overhead and are not allowed per the constraint 'without using external libraries' (streams are part of java.util.stream, which is an external library in the context of the legacy code). Option D is wrong because a linked list has O(n) memory overhead per node and requires conversion to int[], adding extra passes and memory churn.

Page 1 of 2 · 79 questions totalNext →

Ready to test yourself?

Try a timed practice session using only Arrays Methods questions.