Latest Java Arrays MCQs

1 min read

In Java, an array is a dynamically allocated object used to store a fixed-size sequential collection of elements of the exact same data type. Once an array is instantiated, its size cannot be altered, ensuring contiguous memory allocation for highly efficient index-based data retrieval. Unlike arrays in C or C++, Java arrays are treated strictly as objects, inherently providing a length property to safely determine their size at runtime. Furthermore, Java natively supports multi-dimensional arrays implemented internally as “arrays of arrays” which allows for the creation of memory-efficient jagged (or ragged) structures. Utilizing the java.util.Arrays utility class provides developers with powerful built-in methods for sorting, searching, and manipulating array data securely.

1. What is the default value of elements in an uninitialized integer array in Java?

a) 0
b) null
c) 1
d) Garbage value
Correct Answer: a) 0
Explanation:
In Java, primitive type array elements (like int) are automatically initialized to their default values, which is 0 for integers.

2. Which of the following is the correct way to declare and initialize a single-dimensional array in Java?

a) int arr[] = new int[5];
b) int[] arr = {1, 2, 3, 4, 5};
c) Both a and b
d) int arr = new int(5);
Correct Answer: c) Both a and b
Explanation:
Both options a and b are valid syntaxes for declaring and initializing an array in Java.

3. What is the index of the first element in a Java array?

a) 1
b) -1
c) 0
d) Depends on the array type
Correct Answer: c) 0
Explanation:
Java arrays are zero-indexed, meaning the first element is always at index 0.

4. Which exception is thrown when you attempt to access an array index that is negative or greater than or equal to the array's length?

a) NullPointerException
b) ArrayIndexOutOfBoundsException
c) ArrayStoreException
d) IndexOutOfBoundsException
Correct Answer: b) ArrayIndexOutOfBoundsException
Explanation:
Accessing an invalid index throws java.lang.ArrayIndexOutOfBoundsException at runtime.

5. What is the return type of the length property of an array in Java?

a) int
b) long
c) short
d) boolean
Correct Answer: a) int
Explanation:
The length property of an array returns an integer value representing the total number of elements in the array.

6. Which of the following correctly finds the length of an array named 'numbers'?

a) numbers.length()
b) numbers.size()
c) numbers.length
d) length(numbers)
Correct Answer: c) numbers.length
Explanation:
For arrays, length is a final field (not a method), so it is accessed without parentheses as numbers.length.

7. What happens if you try to create an array with a negative size, such as 'int[] arr = new int[-3];'?

a) It creates an empty array of size 0
b) It throws a NegativeArraySizeException
c) It throws a Compile-time error
d) It allocates memory dynamically
Correct Answer: b) It throws a NegativeArraySizeException
Explanation:
Specifying a negative size during array creation throws a runtime NegativeArraySizeException.

8. Which of the following statements about Java arrays is true?

a) Arrays can change their size dynamically after creation.
b) Arrays are objects in Java.
c) Array elements are stored in non-contiguous memory locations.
d) Primitive arrays store object references.
Correct Answer: b) Arrays are objects in Java.
Explanation:
Arrays are dynamically created objects in Java that inherit from the Object class and are stored in heap memory.

9. What is the default value of elements in an uninitialized object reference array (e.g., String[])?

a) Empty string
b) null
c) Undefined
d) Zero
Correct Answer: b) null
Explanation:
Reference type array elements are initialized to null by default.

10. How do you declare a two-dimensional array in Java?

a) int[][] matrix = new int[3][3];
b) int matrix[][] = new int[3][3];
c) int[] matrix[] = new int[3][3];
d) All of the above
Correct Answer: d) All of the above
Explanation:
All listed syntaxes are valid ways to declare a multi-dimensional array in Java.

11. What is a jagged array in Java?

a) An array with negative indices
b) A multi-dimensional array with rows of different lengths
c) An array that causes a compilation error
d) An array sorted in descending order
Correct Answer: b) A multi-dimensional array with rows of different lengths
Explanation:
A jagged array is an array of arrays where each row can have a different number of columns.

12. Which package contains utility methods for manipulating arrays, such as sorting and searching?

a) java.util
b) java.io
c) java.net
d) java.lang
Correct Answer: a) java.util
Explanation:
The java.util.Arrays class contains static methods for sorting, searching, comparing, and filling arrays.

13. Which method is used to sort an array in ascending order using java.util.Arrays?

a) Arrays.order(arr)
b) Arrays.sort(arr)
c) Arrays.arrange(arr)
d) Arrays.ascending(arr)
Correct Answer: b) Arrays.sort(arr)
Explanation:
Arrays.sort() is the standard static method provided in java.util.Arrays to sort arrays.

14. What prerequisite is required before using Arrays.binarySearch() on an array?

a) The array must be empty
b) The array must be sorted
c) The array must contain only positive numbers
d) The array must be initialized using clone()
Correct Answer: b) The array must be sorted
Explanation:
Binary search algorithms require the underlying collection or array to be sorted beforehand to function correctly.

15. What does Arrays.binarySearch() return if the target element is not found in the array?

a) -1
b) null
c) A negative insertion point value
d) Throws an exception
Correct Answer: c) A negative insertion point value
Explanation:
If the key is not found, binarySearch returns (-(insertion point) - 1).

16. Which method can be used to compare two arrays for content equality in Java?

a) arr1.equals(arr2)
b) Arrays.equals(arr1, arr2)
c) arr1 == arr2
d) Arrays.compareContent(arr1, arr2)
Correct Answer: b) Arrays.equals(arr1, arr2)
Explanation:
The equals method in java.util.Arrays compares the contents of two arrays, whereas arr1.equals(arr2) on arrays checks reference equality unless overridden.

17. What is the output of printing an array directly without using Arrays.toString()?

a) The comma-separated elements
b) A hash string like [I@1b6d3586
c) A compilation error
d) Null
Correct Answer: b) A hash string like [I@1b6d3586
Explanation:
Arrays do not override the toString() method from Object, so printing an array directly outputs its type representation and hashcode.

18. Which method converts an array to a readable string representation containing its elements?

a) Arrays.toString(arr)
b) arr.toString()
c) String.valueOf(arr)
d) Arrays.print(arr)
Correct Answer: a) Arrays.toString(arr)
Explanation:
Arrays.toString() returns a string representation of the contents of the specified array.

19. Can you change the size of an array after it has been created in Java?

a) Yes, using the resize() method
b) Yes, by re-assigning new length
c) No, arrays have a fixed size once instantiated
d) Yes, if declared as dynamic
Correct Answer: c) No, arrays have a fixed size once instantiated
Explanation:
Java arrays have a fixed length determined at the time of creation and cannot be resized. ArrayList should be used if dynamic sizing is needed.

20. What happens when you pass an array to a method and modify its elements inside that method?

a) The changes are reflected outside the method because arrays are reference types.
b) The changes are local to the method because Java is strictly pass-by-value.
c) It causes a compilation error.
d) A clone of the array is modified instead.
Correct Answer: a) The changes are reflected outside the method because arrays are reference types.
Explanation:
Although Java passes object references by value, modifying the contents of the array reference affects the underlying heap object visible to the caller.

21. Which of the following is an anonymous array in Java?

a) new int[] {1, 2, 3}
b) int[] {1, 2, 3}
c) new int(3)
d) Anonymous arrays do not exist in Java
Correct Answer: a) new int[] {1, 2, 3}
Explanation:
An anonymous array is created without explicitly naming it using the syntax new type[] {elements}.

22. What exception is thrown if you try to store an incompatible type into an array of objects (e.g., storing a String in an Integer array)?

a) ClassCastException
b) ArrayStoreException
c) TypeMismatchException
d) IllegalArgumentException
Correct Answer: b) ArrayStoreException
Explanation:
Trying to store a runtime type that is not assignment-compatible with the array's component type throws ArrayStoreException.

23. How do you copy an array efficiently in Java?

a) Using a standard for loop
b) Using System.arraycopy()
c) Using Arrays.copyOf()
d) Both b and c
Correct Answer: d) Both b and c
Explanation:
Both System.arraycopy() and Arrays.copyOf() provide efficient built-in mechanisms for copying array data.

24. What does System.arraycopy() require?

a) Source array, source position, destination array, destination position, and length
b) Only source and destination arrays
c) Source array and length
d) Destination array and position
Correct Answer: a) Source array, source position, destination array, destination position, and length
Explanation:
System.arraycopy(src, srcPos, dest, destPos, length) copies a specified portion of an array.

25. Which loop is specially designed to iterate through arrays without index management?

a) While loop
b) For-each loop (enhanced for loop)
c) Do-while loop
d) Iterator loop
Correct Answer: b) For-each loop (enhanced for loop)
Explanation:
The enhanced for-each loop simplifies iteration over arrays and collections without needing explicit index counters.

26. Can a for-each loop be used to modify the values inside a primitive array?

a) Yes, changes update the array elements directly.
b) No, because the iteration variable holds a copy of the element value.
c) Yes, if combined with an index pointer.
d) No, it throws a ConcurrentModificationException.
Correct Answer: b) No, because the iteration variable holds a copy of the element value.
Explanation:
In a for-each loop, the loop variable is a copy of the array element value; modifying it does not change the array elements.

27. What is the memory location where Java arrays are stored?

a) Stack memory
b) Heap memory
c) Register memory
d) Hard disk
Correct Answer: b) Heap memory
Explanation:
All objects, including arrays, are allocated in the heap memory in Java.

28. Where is the array variable reference stored when declared inside a method?

a) Stack memory
b) Heap memory
c) Method area
d) Constant pool
Correct Answer: a) Stack memory
Explanation:
Local variables and object references (like the array pointer itself) are stored on the thread's stack, while the actual array object resides on the heap.

29. What is the output of 'int[] arr = new int[3]; System.out.println(arr[1]);'?

a) null
b) 0
c) Exception
d) Unassigned
Correct Answer: b) 0
Explanation:
The array elements are initialized to 0, so accessing index 1 returns 0.

30. Which of the following creates a 3-element boolean array with all elements set to false by default?

a) boolean[] arr = new boolean[3];
b) boolean arr = {false, false, false};
c) boolean[] arr = new boolean[] {true, true, true};
d) Both a and c
Correct Answer: a) boolean[] arr = new boolean[3];
Explanation:
The default value for boolean elements in an uninitialized array is false.

31. How do you fill all elements of an existing integer array with a specific value, say 7?

a) Arrays.fill(arr, 7);
b) arr.fill(7);
c) Arrays.setAll(arr, 7);
d) System.fill(arr, 7);
Correct Answer: a) Arrays.fill(arr, 7);
Explanation:
Arrays.fill() assigns the specified value to each element of the specified array.

32. What does Arrays.deepToString() do that Arrays.toString() does not?

a) It handles multi-dimensional arrays properly.
b) It sorts the array before printing.
c) It prints reverse order.
d) It converts primitives to wrapper classes.
Correct Answer: a) It handles multi-dimensional arrays properly.
Explanation:
Arrays.deepToString() is required for nested/multi-dimensional arrays; otherwise, Arrays.toString() would print reference hashes for inner arrays.

33. What is the result of comparing two distinct array references with the same contents using the equality operator (==)?

a) true
b) false
c) Compilation error
d) Runtime exception
Correct Answer: b) false
Explanation:
The equality operator checks for reference equality (whether both point to the exact same object in heap memory), not content equality.

34. Which statement correctly clones an array in Java?

a) int[] copy = arr.clone();
b) int[] copy = Arrays.clone(arr);
c) int[] copy = new clone(arr);
d) int[] copy = arr.copy();
Correct Answer: a) int[] copy = arr.clone();
Explanation:
Arrays implement the Cloneable interface, and the clone() method creates a shallow copy of the array.

35. What type of copy is performed by the array clone() method in Java?

a) Deep copy
b) Shallow copy
c) Reference copy
d) Exact memory duplication
Correct Answer: b) Shallow copy
Explanation:
The clone() method creates a shallow copy, meaning for object arrays, the references are copied, not the underlying objects themselves.

36. What is the maximum allowed index of an array of size N in Java?

a) N
b) N - 1
c) N + 1
d) Depends on data type
Correct Answer: b) N - 1
Explanation:
Since Java arrays are 0-indexed, an array of size N has indices ranging from 0 to N - 1.

37. What happens if you try to declare an array size using a float or double value?

a) It rounds down
b) It rounds up
c) Compile-time error
d) Runtime exception
Correct Answer: c) Compile-time error
Explanation:
Array size must be an integer (int, byte, short, char). Using floating-point values causes a compile-time type mismatch error.

38. Which of the following is a valid way to pass an array to a method?

a) public void printArray(int[] arr) { }
b) public void printArray(int... arr) { }
c) Both a and b
d) public void printArray(arr[]) { }
Correct Answer: c) Both a and b
Explanation:
Both traditional array syntax and varargs (variable arguments) syntax allow passing arrays or comma-separated lists into methods.

39. What is the purpose of varargs (three dots) in Java methods regarding arrays?

a) It allows passing zero or multiple arguments which are treated inside the method as an array.
b) It converts arrays to strings automatically.
c) It speeds up array iteration.
d) It allows multi-dimensional array declaration.
Correct Answer: a) It allows passing zero or multiple arguments which are treated inside the method as an array.
Explanation:
Varargs syntactic sugar lets callers pass individual arguments or an array, packaging them into an array inside the method body.

40. Can an array store elements of different data types (e.g., int and String) simultaneously without using Object arrays?

a) Yes, using primitive arrays
b) Yes, using advanced casting
c) No, standard arrays are homogeneously typed
d) Yes, by default
Correct Answer: c) No, standard arrays are homogeneously typed
Explanation:
Java arrays are strictly homogeneous; an array declared of a specific type can only hold elements of that type or its subtypes.

41. How can you achieve heterogeneous data storage using arrays in Java?

a) By using an array of type Object
b) By using primitive type casting
c) It is impossible in Java
d) Using double brackets
Correct Answer: a) By using an array of type Object
Explanation:
Since all classes inherit from Object, an Object array can store references to various types of objects.

42. What will be the output of 'int[] a = {1, 2}; int[] b = {1, 2}; System.out.println(a == b);'?

a) true
b) false
c) Compilation error
d) Runtime exception
Correct Answer: b) false
Explanation:
The a and b variables point to two different array objects in heap memory, so reference equality evaluates to false.

43. What will be the output of 'int[] a = {1, 2}; int[] b = {1, 2}; System.out.println(Arrays.equals(a, b));'?

a) true
b) false
c) Compilation error
d) Runtime exception
Correct Answer: a) true
Explanation:
Arrays.equals() checks content equality, and since both arrays contain the exact same elements in the same order, it returns true.

44. Which of the following declarations is illegal in Java?

a) int[] a = new int[10];
b) int a[] = new int[10];
c) int[] a = new int[];
d) int[] a = {1, 2, 3};
Correct Answer: c) int[] a = new int[];
Explanation:
Omitting the size when instantiating an array with new without providing initializer values is a compilation error.

45. What is the time complexity of accessing an element in an array by its index?

a) O(1)
b) O(N)
c) O(log N)
d) O(N^2)
Correct Answer: a) O(1)
Explanation:
Array elements are stored in contiguous memory locations, allowing direct random access in constant time O(1).

46. What is the time complexity of searching for an element in an unsorted array using linear search?

a) O(1)
b) O(log N)
c) O(N)
d) O(N log N)
Correct Answer: c) O(N)
Explanation:
Linear search requires checking each element one by one in the worst case, taking O(N) time.

47. What is the time complexity of Arrays.sort() for primitive arrays in Java?

a) O(N)
b) O(N log N)
c) O(N^2)
d) O(1)
Correct Answer: b) O(N log N)
Explanation:
Java uses Dual-Pivot Quicksort for primitive arrays, which runs in O(N log N) average time complexity.

48. Which sorting algorithm is used by Java for sorting arrays of objects?

a) Bubble Sort
b) TimSort
c) Selection Sort
d) Standard Quicksort
Correct Answer: b) TimSort
Explanation:
Java uses an adaptive, stable mergesort variant called TimSort for sorting object arrays.

49. What is a major limitation of arrays compared to Collections like ArrayList?

a) Arrays cannot store primitives.
b) Arrays have a fixed size and lack built-in methods for insertion/deletion.
c) Arrays are slower for random access.
d) Arrays cannot be iterated.
Correct Answer: b) Arrays have a fixed size and lack built-in methods for insertion/deletion.
Explanation:
Arrays are static in size and do not provide helper methods like add(), remove(), or dynamic resizing.

50. How do you declare a 3D array in Java?

a) int[][][] arr = new int[2][3][4];
b) int arr[][][] = new int[2][3][4];
c) Both a and b
d) int[] arr[] [] = new int[2,3,4];
Correct Answer: c) Both a and b
Explanation:
Both options a and b represent valid 3D array declarations in Java.

51. What does the expression 'args.length' signify in a standard Java main method?

a) The number of command-line arguments passed to the program
b) The size of the system environment variables
c) The maximum memory allocation
d) The total number of loaded classes
Correct Answer: a) The number of command-line arguments passed to the program
Explanation:
The String[] args parameter in the main method holds command-line arguments, and args.length gives the count of those arguments.

52. What will 'int[] arr = new int[0]; System.out.println(arr.length);' output?

a) 0
b) 1
c) null
d) Throws NegativeArraySizeException
Correct Answer: a) 0
Explanation:
An array of size 0 is completely valid in Java and has a length of 0.

53. Which of the following statements correctly initializes a 2x2 matrix inline?

a) int[][] m = {{1, 2}, {3, 4}};
b) int[][] m = new int[2, 2];
c) int m[][] = [1, 2][3, 4];
d) int[][] m = new {{1, 2}, {3, 4}};
Correct Answer: a) int[][] m = {{1, 2}, {3, 4}};
Explanation:
Array initializer blocks using nested braces are the standard way to inline initialize multi-dimensional arrays.

54. Can an array index be of type 'long' in Java?

a) Yes
b) No, it must be an int or a type implicitly promotable to int
c) Yes, for large arrays
d) Only in Java 17 and above
Correct Answer: b) No, it must be an int or a type implicitly promotable to int
Explanation:
Java array indices are constrained to integer types because array sizes and index values cannot exceed Integer.MAX_VALUE.

55. What is the maximum number of elements an array can hold in Java theoretically?

a) Long.MAX_VALUE
b) Integer.MAX_VALUE
c) Short.MAX_VALUE
d) Unlimited
Correct Answer: b) Integer.MAX_VALUE
Explanation:
Because array indexing uses int, the maximum capacity of an array is Integer.MAX_VALUE.

56. What happens if you attempt to create an array with a size greater than Integer.MAX_VALUE?

a) Compile-time error
b) OutOfMemoryError
c) NegativeArraySizeException
d) It automatically scales up
Correct Answer: a) Compile-time error
Explanation:
Passing a literal or expression exceeding integer bounds directly as an array size results in a compile-time integer number too large error.

57. Which method in java.util.Arrays can be used to compare two arrays lexicographically?

a) Arrays.compare()
b) Arrays.lexico()
c) Arrays.compareOrder()
d) Arrays.diff()
Correct Answer: a) Arrays.compare()
Explanation:
Introduced in Java 9, Arrays.compare() compares two arrays lexicographically and returns a negative integer, zero, or a positive integer.

58. How can you convert an array to a List in Java easily?

a) Arrays.asList(arr)
b) arr.toList()
c) List.create(arr)
d) Collection.from(arr)
Correct Answer: a) Arrays.asList(arr)
Explanation:
Arrays.asList() returns a fixed-size list backed by the specified array.

59. What is a key characteristic of the List returned by Arrays.asList()?

a) It is immutable in size (cannot add or remove elements).
b) It is fully dynamic and resizable.
c) It converts primitive arrays to primitive lists.
d) It creates a deep copy in heap memory.
Correct Answer: a) It is immutable in size (cannot add or remove elements).
Explanation:
The list returned is a fixed-size view backed by the original array; calling add() or remove() throws an UnsupportedOperationException.

60. What does Arrays.mismatch() return if two arrays are identical?

a) -1
b) 0
c) 1
d) Arrays.length
Correct Answer: a) -1
Explanation:
Arrays.mismatch() finds and returns the index of the first mismatching element between two arrays, or -1 if they are identical.

61. Which of the following is a valid way to initialize an array of strings with 3 elements?

a) String[] names = new String[]{'Alice', 'Bob', 'Charlie'};
b) String names[] = {'Alice', 'Bob', 'Charlie'};
c) Both a and b
d) String[] names = new String(3);
Correct Answer: c) Both a and b
Explanation:
Both options are valid ways to declare and initialize a string array.

62. What does the following code print? 'int[] x = {1, 2, 3}; int[] y = x; y[0] = 10; System.out.println(x[0]);'

a) 1
b) 10
c) 3
d) Throws exception
Correct Answer: b) 10
Explanation:
Variables x and y reference the same array object in memory, so modifications through y affect x as well.

63. Which interface do Java arrays implicitly implement?

a) Cloneable and Serializable
b) List and Collection
c) Iterable and Comparable
d) RandomAccess only
Correct Answer: a) Cloneable and Serializable
Explanation:
Java arrays implement both java.lang.Cloneable and java.io.Serializable interfaces.

64. Can you subclass or inherit from an array type in Java?

a) Yes
b) No, array types are implicitly final.
c) Only for Object arrays
d) Yes, using abstract array classes
Correct Answer: b) No, array types are implicitly final.
Explanation:
Array classes are generated by the JVM and are implicitly final, meaning you cannot extend them.

65. What is the output of 'char[] c = new char[1]; System.out.println(c[0] == 0);'?

a) true
b) false
c) Compilation error
d) Runtime exception
Correct Answer: a) true
Explanation:
The default value for char elements in an array is the null character, whose numeric integer code is 0.

66. How do you find the number of rows in a two-dimensional array named 'grid'?

a) grid.length
b) grid[0].length
c) grid.rows()
d) grid.size()
Correct Answer: a) grid.length
Explanation:
A 2D array in Java is an array of arrays. Its primary length gives the number of rows.

67. How do you find the number of columns in the first row of a two-dimensional array named 'grid'?

a) grid.length
b) grid[0].length
c) grid.columns()
d) grid.width()
Correct Answer: b) grid[0].length
Explanation:
grid[0] refers to the first row array, and its length property provides the number of columns in that row.

68. What is the result of executing Arrays.parallelSort(arr) compared to Arrays.sort(arr)?

a) parallelSort uses parallel sorting algorithms to leverage multiple processors for large arrays.
b) parallelSort sorts arrays in reverse order.
c) parallelSort only works on multidimensional arrays.
d) There is no difference.
Correct Answer: a) parallelSort uses parallel sorting algorithms to leverage multiple processors for large arrays.
Explanation:
Arrays.parallelSort() uses the parallel merge sort algorithm to cut down sorting time on multi-core processors for large datasets.

69. Which of the following is true regarding array bounds checking in Java?

a) It is performed at compile-time.
b) It is performed at runtime by the JVM.
c) It is not performed in Java, leading to memory corruption bugs.
d) It can be disabled using compiler flags.
Correct Answer: b) It is performed at runtime by the JVM.
Explanation:
Java enforces strict bounds checking at runtime, throwing an ArrayIndexOutOfBoundsException whenever an invalid index is accessed.

70. What does System.identityHashCode(arr) return for an array?

a) A hash code based on the array's memory address
b) The sum of all array elements
c) The length of the array
d) Always 0
Correct Answer: a) A hash code based on the array's memory address
Explanation:
System.identityHashCode returns the standard object hash code based on memory address, unaffected by overridden hashCode methods.

71. What happens when an array reference variable is assigned 'null'?

a) The array object is immediately deleted from memory.
b) The reference variable no longer points to any array object on the heap.
c) It causes a compilation error.
d) It resets all elements in the array to zero.
Correct Answer: b) The reference variable no longer points to any array object on the heap.
Explanation:
Assigning null to the reference variable disconnects it from the array object, making the array eligible for garbage collection if no other references remain.

72. What exception occurs if you try to call a method or access a field on an array reference that is currently 'null'?

a) NullPointerException
b) ArrayIndexOutOfBoundsException
c) ClassCastException
d) IllegalAccessException
Correct Answer: a) NullPointerException
Explanation:
Attempting to query properties like length or index elements on a null reference throws a NullPointerException.

73. Can array types be used as generic type parameters directly?

a) Yes, arrays can be used as type parameters, but primitive types cannot.
b) No, arrays cannot be used in generics.
c) Yes, primitive types can be used directly as generic arguments.
d) Only in static contexts.
Correct Answer: a) Yes, arrays can be used as type parameters, but primitive types cannot.
Explanation:
Generics require reference types; primitive types like int cannot be type parameters, but array types like int[] are reference types and are valid.

74. Which of the following creates a stream from an array in Java?

a) Arrays.stream(arr)
b) arr.stream()
c) Stream.from(arr)
d) Stream.ofArray(arr)
Correct Answer: a) Arrays.stream(arr)
Explanation:
Arrays.stream() is the utility method used to create a Stream from an array.

75. How do you reverse the elements of an array in-place using standard Java libraries?

a) Arrays.reverse(arr)
b) Collections.reverse(Arrays.asList(arr)) for object arrays
c) arr.reverse()
d) System.reverse(arr)
Correct Answer: b) Collections.reverse(Arrays.asList(arr)) for object arrays
Explanation:
Java's Arrays class does not have a direct built-in reverse method; object arrays can be reversed via Collections.reverse().

76. What is the output of 'int[] arr = new int[] {5, 10, 15}; int sum = 0; for(int v : arr) sum += v; System.out.println(sum);'?

a) 30
b) 15
c) 25
d) Compilation error
Correct Answer: a) 30
Explanation:
The enhanced for loop sums up 5 + 10 + 15, which equals 30.

77. Which of the following is a valid method signature for a main method accepting string arguments via arrays?

a) public static void main(String[] args)
b) public static void main(String... args)
c) Both a and b
d) public void main(String[] args)
Correct Answer: c) Both a and b
Explanation:
Both traditional array notation and varargs notation are valid for the main method parameter signature.

78. What does Arrays.hashCode(arr) compute?

a) A hash code based on the contents of the array
b) The memory address hash of the array object
c) The sum of element indices
d) A constant integer
Correct Answer: a) A hash code based on the contents of the array
Explanation:
Arrays.hashCode() calculates a hash code derived from the contents of the array, ensuring arrays with identical elements produce the same hash.

79. Can you use the 'new' operator to initialize array elements with non-default values simultaneously in size specification?

a) Yes, e.g., new int[3] {1, 2, 3};
b) No, combining explicit size with an array initializer block is a compilation error.
c) Yes, for object arrays only.
d) Yes, using parentheses.
Correct Answer: b) No, combining explicit size with an array initializer block is a compilation error.
Explanation:
You cannot specify both the dimension size (e.g., new int[3]) and initializer values ({1, 2, 3}) simultaneously in Java syntax.

80. Which keyword is associated with array creation and heap memory allocation in Java?

a) create
b) new
c) alloc
d) malloc
Correct Answer: b) new
Explanation:
The 'new' keyword is used to instantiate arrays and allocate memory on the heap.

81. What is the base class of all array objects in Java?

a) java.lang.Object
b) java.util.Array
c) java.lang.Class
d) Arrays do not have a base class.
Correct Answer: a) java.lang.Object
Explanation:
Every array in Java directly inherits from java.lang.Object.

82. What happens when an array is passed to a method as 'int[] a'? Is a copy of the array created?

a) Yes, a deep copy of all elements is passed.
b) No, the reference to the original array is passed by value.
c) Yes, a shallow copy is passed.
d) It creates a new stack array.
Correct Answer: b) No, the reference to the original array is passed by value.
Explanation:
Java is pass-by-value; the value passed is the reference pointer pointing to the array object on the heap, not a duplicate of the array itself.

83. Which utility method is used to fill a specific range of an array with a value?

a) Arrays.fill(arr, fromIndex, toIndex, val)
b) Arrays.fillRange(arr, val)
c) Arrays.set(arr, from, to, val)
d) System.fillRange()
Correct Answer: a) Arrays.fill(arr, fromIndex, toIndex, val)
Explanation:
The overloaded Arrays.fill() method allows specifying fromIndex (inclusive) and toIndex (exclusive) to fill a specific range.

84. What is the behavior of 'toIndex' in range-based methods like Arrays.fill or Arrays.copyOfRange?

a) It is inclusive.
b) It is exclusive.
c) It is optional.
d) It represents the length directly.
Correct Answer: b) It is exclusive.
Explanation:
In Java range methods, the 'toIndex' parameter is exclusive, meaning the element at 'toIndex' is not included in the operation.

85. What does Arrays.copyOfRange(arr, 1, 4) copy?

a) Elements from index 1 up to index 4 (inclusive)
b) Elements from index 1 up to index 4 (exclusive of index 4)
c) Elements from index 1 to length 4
d) Elements from index 4 to 1
Correct Answer: b) Elements from index 1 up to index 4 (exclusive of index 4)
Explanation:
It copies elements starting from index 1, 2, and 3, stopping before index 4.

86. Can an array store null references if it is an array of objects?

a) Yes
b) No, object arrays cannot contain null values.
c) Only if declared as final.
d) Only in multi-dimensional arrays.
Correct Answer: a) Yes
Explanation:
Object arrays can store any reference type, including null.

87. What is the primary difference between 'int[] a' and 'int a[]' syntax?

a) 'int[] a' is preferred by convention, but both are semantically identical in Java.
b) 'int[] a' creates a dynamic array, while 'int a[]' creates a static array.
c) 'int a[]' is invalid in modern Java.
d) 'int[] a' places the array on the heap.
Correct Answer: a) 'int[] a' is preferred by convention, but both are semantically identical in Java.
Explanation:
Both notations are valid, though 'int[] a' clearly associates the brackets with the type rather than the variable name.

88. How do you write a multi-dimensional array where inner arrays can be initialized later?

a) int[][] table = new int[3][];
b) int[][] table = new int[][3];
c) int[][] table = new int[3,3];
d) int[][] table = {};
Correct Answer: a) int[][] table = new int[3][];
Explanation:
You can specify the size of the first dimension and leave subsequent dimensions empty to create a jagged array structure.

89. What will happen if you try to access an uninitialized inner array in a jagged array like 'int[][] table = new int[3][]; System.out.println(table[0]);'?

a) It prints null
b) It throws NullPointerException immediately upon access
c) It prints an empty array
d) Compilation error
Correct Answer: a) It prints null
Explanation:
The inner array references in a jagged array default to null until explicitly instantiated.

90. Which of the following is a valid statement to create an array of 5 integers?

a) int[] a = new int[5];
b) int a[] = new int[5];
c) int[] a = {0, 0, 0, 0, 0};
d) All of the above
Correct Answer: d) All of the above
Explanation:
All listed statements successfully create an array capable of holding 5 integers.

91. What is the output of 'int[] a = {5}; modify(a); System.out.println(a[0]);' given 'void modify(int[] arr) { arr[0] = 99; }'?

a) 5
b) 99
c) 0
d) Throws exception
Correct Answer: b) 99
Explanation:
The method modifies the array element via the reference, so the change persists outside the method scope.

92. What is the output of 'int[] a = {5}; modify(a); System.out.println(a[0]);' given 'void modify(int[] arr) { arr = new int[]{99}; }'?

a) 5
b) 99
c) 0
d) Throws exception
Correct Answer: a) 5
Explanation:
The method reassigns the local parameter variable to a new array, leaving the caller's reference pointing to the original array containing 5.

93. Which utility class method is used to print an entire 2D matrix cleanly?

a) Arrays.deepToString(matrix)
b) Arrays.toString(matrix)
c) Arrays.printMatrix(matrix)
d) Matrix.toString(matrix)
Correct Answer: a) Arrays.deepToString(matrix)
Explanation:
Arrays.deepToString() recursively formats multi-dimensional arrays into a readable string.

94. Can array variables be declared with 'final' in Java?

a) Yes, but it only prevents reassigning the reference variable, not modifying the array's elements.
b) No, final arrays are prohibited.
c) Yes, and it makes all elements immutable.
d) Only for primitive arrays.
Correct Answer: a) Yes, but it only prevents reassigning the reference variable, not modifying the array's elements.
Explanation:
A final array variable cannot point to a different array object once initialized, but its individual elements can still be mutated.

95. What is the primary advantage of using arrays over primitive variables?

a) They allow storing and managing collections of related data values under a single identifier.
b) They execute instructions faster than CPU registers.
c) They automatically resize as needed.
d) They prevent all runtime exceptions.
Correct Answer: a) They allow storing and managing collections of related data values under a single identifier.
Explanation:
Arrays group multiple variables of the same type together, enabling efficient loops and batch data processing.

96. Which of the following describes array covariance in Java?

a) An array of Sub can be assigned to a variable of type Super[].
b) Arrays can change types dynamically at runtime.
c) Primitive arrays can be converted to object arrays automatically.
d) Arrays do not support subtype relationships.
Correct Answer: a) An array of Sub can be assigned to a variable of type Super[].
Explanation:
Java arrays are covariant, meaning assigning a subclass array to a superclass array reference is valid at compile-time.

97. Can you use the 'instanceof' operator with an array type?

a) Yes, e.g., obj instanceof int[]
b) No, instanceof is only for classes.
c) Only with Object arrays.
d) Yes, but only for multi-dimensional arrays.
Correct Answer: a) Yes, e.g., obj instanceof int[]
Explanation:
Arrays are objects in Java, and instanceof can check if a reference points to a specific array type.

98. What string is returned by 'int[].class.getName()'?

a) [I
b) int[]
c) IntegerArray
d) Array
Correct Answer: a) [I
Explanation:
The internal JVM representation for a 1D integer array class name is '[I'.

99. How do you dynamically create an array using Reflection in Java?

a) java.lang.reflect.Array.newInstance(type, length)
b) new java.lang.reflect.Array(type, length)
c) Class.createArray(type, length)
d) Object.newArray(type, length)
Correct Answer: a) java.lang.reflect.Array.newInstance(type, length)
Explanation:
The Array.newInstance method in the reflection API allows dynamic creation of arrays at runtime.

100. What exception is thrown if you try to put a double into an Object[] that actually points to a String[]?

a) ArrayStoreException
b) ClassCastException
c) IllegalArgumentException
d) TypeMismatchException
Correct Answer: a) ArrayStoreException
Explanation:
Due to covariance, an Object[] can hold a String[]. Adding a non-String element throws ArrayStoreException at runtime.

101. Is it possible to instantiate an array of a generic type like 'new T[10]' in Java?

a) No, because generic type information is erased at runtime.
b) Yes, but it requires a type cast.
c) Yes, this is completely valid.
d) Only if T extends Object.
Correct Answer: a) No, because generic type information is erased at runtime.
Explanation:
Java generics use type erasure, meaning the JVM does not know what type 'T' is at runtime to allocate the array.

102. What is the result of attempting to create 'new ArrayList[10]' where ArrayList has a generic parameter?

a) Compile-time error: generic array creation
b) An array of 10 ArrayLists is created
c) A single ArrayList with capacity 10 is created
d) Runtime Exception
Correct Answer: a) Compile-time error: generic array creation
Explanation:
Java strictly forbids creating arrays of parameterized types to prevent type safety issues.

103. How many loops are typically required to traverse all elements of a 2D array?

a) Two nested loops
b) One loop
c) Three nested loops
d) Zero loops
Correct Answer: a) Two nested loops
Explanation:
Traversing a 2D matrix generally requires an outer loop for rows and an inner loop for columns.

104. What will happen if 'args[0]' is accessed when 'args.length == 0'?

a) ArrayIndexOutOfBoundsException
b) NullPointerException
c) Returns null
d) Returns empty string
Correct Answer: a) ArrayIndexOutOfBoundsException
Explanation:
Accessing index 0 on an empty array (length 0) goes out of bounds.

105. What is the difference between length and capacity in Java arrays?

a) Arrays do not have a separate capacity; length is the fixed capacity.
b) Length is elements present, capacity is total space.
c) Capacity changes dynamically, length does not.
d) There is no length property, only capacity.
Correct Answer: a) Arrays do not have a separate capacity; length is the fixed capacity.
Explanation:
Unlike ArrayLists which track size vs capacity, standard arrays only have a fixed 'length'.

106. How do you resize an array in Java once it is created?

a) You cannot; you must create a new array and copy the elements.
b) By changing the length property.
c) Using Arrays.resize()
d) Using the 'extends' keyword.
Correct Answer: a) You cannot; you must create a new array and copy the elements.
Explanation:
Arrays are statically sized. To 'resize', a new array must be created and elements copied over.

107. What is uniquely true about printing a 'char[]' variable using System.out.println()?

a) It prints the actual characters as a String.
b) It prints the memory address hashcode.
c) It throws an exception.
d) It prints comma-separated characters.
Correct Answer: a) It prints the actual characters as a String.
Explanation:
The PrintStream class has an overloaded method for char[], which prints the array contents directly as a text string instead of printing the object hash.

108. Can you create an array of an interface type in Java?

a) Yes, and it can store references to any object implementing that interface.
b) No, interfaces cannot be instantiated.
c) Yes, but it can only store nulls.
d) Only if the interface has no methods.
Correct Answer: a) Yes, and it can store references to any object implementing that interface.
Explanation:
You can declare an array of an interface type, storing any class instance that implements the interface.

109. Can you create an array of an abstract class type?

a) Yes, it can store references to objects of its concrete subclasses.
b) No, abstract classes cannot be used as array types.
c) Yes, but you can instantiate abstract class objects directly into it.
d) Only for single-dimensional arrays.
Correct Answer: a) Yes, it can store references to objects of its concrete subclasses.
Explanation:
While abstract classes cannot be instantiated, an array of an abstract class type can be created to hold subclass objects.

110. What happens if you compile 'int[][] arr = new int[][3];'?

a) Compile-time error
b) Creates a jagged array
c) Creates a 3x3 matrix
d) Throws exception at runtime
Correct Answer: a) Compile-time error
Explanation:
When declaring multi-dimensional arrays, you must specify the size of the most significant (leftmost) dimension.

111. Which requires less memory overhead per element: an int array or an ArrayList of Integers?

a) int array, because it stores primitive values directly in a contiguous block.
b) ArrayList, because it optimizes memory.
c) Both are exactly the same.
d) int array, but only for small sizes.
Correct Answer: a) int array, because it stores primitive values directly in a contiguous block.
Explanation:
A primitive array avoids the object header overhead and boxing wrapper classes associated with ArrayList.

112. Can you cast an 'int[]' to an 'Integer[]' in Java?

a) No, primitive arrays and Object wrapper arrays are not compatible for casting.
b) Yes, Java autoboxing handles it automatically.
c) Yes, using explicit casting.
d) Only in Java 8 and above.
Correct Answer: a) No, primitive arrays and Object wrapper arrays are not compatible for casting.
Explanation:
Autoboxing works for individual elements, but you cannot cast an entire primitive array to a wrapper object array.

113. What is the default return type of the no-argument toArray() method on a List?

a) Object[]
b) String[]
c) T[]
d) The specific type of the list elements
Correct Answer: a) Object[]
Explanation:
The no-arg list.toArray() always returns an Object array. The overloaded list.toArray(T[] a) is needed for specific typing.

114. What happens if you pass an array smaller than the List to List.toArray(T[] a)?

a) A new array of the same runtime type is allocated with the size of the List.
b) An ArrayIndexOutOfBoundsException is thrown.
c) Only elements that fit are copied.
d) The List size is reduced.
Correct Answer: a) A new array of the same runtime type is allocated with the size of the List.
Explanation:
If the provided array is too small, a new array of the identical component type and sufficient size is allocated via reflection.

115. Are duplicate elements allowed in a standard Java array?

a) Yes
b) No
c) Only for primitive types
d) Only for object types
Correct Answer: a) Yes
Explanation:
Arrays are basic data structures that do not enforce uniqueness, allowing any number of duplicates.

116. Can a primitive type array (e.g., int[]) store 'null' values?

a) No, primitives cannot be null.
b) Yes, it gets converted to 0.
c) Yes, if cast explicitly.
d) Only if initialized with null.
Correct Answer: a) No, primitives cannot be null.
Explanation:
Null is a reference type literal. Primitive variables and arrays cannot hold null values.

117. Are Java arrays inherently thread-safe?

a) No, external synchronization is required for concurrent access.
b) Yes, they are natively synchronized.
c) Only primitive arrays are thread-safe.
d) Only Object arrays are thread-safe.
Correct Answer: a) No, external synchronization is required for concurrent access.
Explanation:
Arrays have no built-in thread safety mechanisms. Concurrent reads and writes can lead to race conditions.

118. If an array reference is marked as 'volatile', are the array's elements volatile?

a) No, only the reference itself is volatile.
b) Yes, the elements inherit the volatile property.
c) It causes a compilation error.
d) Only if they are primitive.
Correct Answer: a) No, only the reference itself is volatile.
Explanation:
In Java, marking an array volatile ensures thread visibility for the array reference, not for individual array elements.

119. What does Arrays.deepHashCode(Object[] a) do?

a) Returns a hash code based on the deep contents of the array.
b) Returns a cryptographic hash of the array.
c) Returns the memory address of the deep array.
d) Throws an exception for multidimensional arrays.
Correct Answer: a) Returns a hash code based on the deep contents of the array.
Explanation:
For multi-dimensional arrays or arrays of arrays, deepHashCode computes a hash based on the values of the inner arrays recursively.

120. Which java.util.Arrays method returns a Spliterator covering all of the specified array?

a) Arrays.spliterator(arr)
b) Arrays.iterator(arr)
c) Arrays.split(arr)
d) Arrays.stream(arr)
Correct Answer: a) Arrays.spliterator(arr)
Explanation:
Introduced in Java 8, Arrays.spliterator() creates a Spliterator for parallel or sequential traversal of the array elements.

121. When is memory for an array allocated in Java?

a) At runtime upon execution of the 'new' keyword.
b) At compile time based on the defined size.
c) When the class is loaded into the JVM.
d) During garbage collection.
Correct Answer: a) At runtime upon execution of the 'new' keyword.
Explanation:
All array allocations occur at runtime on the heap using the new keyword or array initializer syntax.

122. Is 'new int['a']' a valid array creation statement in Java?

a) Yes, the character 'a' is implicitly promoted to an integer size.
b) No, it causes a compile-time error.
c) Yes, but it creates a char array.
d) No, it throws a runtime exception.
Correct Answer: a) Yes, the character 'a' is implicitly promoted to an integer size.
Explanation:
Characters in Java are 16-bit integers under the hood. The character promotes to its integer code, creating an array of that size.

123. What is the typical JVM limit on the number of dimensions a multi-dimensional array can have?

a) 255 dimensions
b) Unlimited
c) 10 dimensions
d) 32 dimensions
Correct Answer: a) 255 dimensions
Explanation:
The Java Virtual Machine specification limits array dimensions to 255.

124. Can you use a 'short' or 'byte' variable to specify the index when accessing an array element?

a) Yes, they are implicitly promoted to int.
b) No, it requires an explicit cast to int.
c) No, only int is strictly allowed.
d) Yes, but only for byte arrays.
Correct Answer: a) Yes, they are implicitly promoted to int.
Explanation:
Smaller integer types (byte, short, char) are automatically promoted to int, making them perfectly valid for array indexing.
← Previous: Latest C++ Functions MCQs
Next →: Latest Java Generics MCQs
JavaScript Error Handling MCQs for Developer Interviews & Certification

JavaScript Error Handling MCQs for Developer Interviews & Certification

Exception and error handling in JavaScript is essential for preventing runtime crashes and maintaining application stability across complex web environments.…

By MCQs Generator
No Image

C++ Exception / Error Handling - MCQs

1. What is the default value of elements in an uninitialized integer array in Java? a) 0 b) null c)…

By MCQs Generator
JavaScript Advanced MCQs

JavaScript Advanced MCQs

Advanced JavaScript mastery requires a deep understanding of the language’s inner runtime mechanics, memory management, and asynchronous concurrency models. Senior-level…

By MCQs Generator