Java Interview Questions

Previous Java Interview Questions Next

Java Arrays - Theory Questions

1. What is an array in Java and what are its key characteristics?

An array in Java is a container object that holds a fixed number of values of a single type. Key characteristics:
- Fixed size (length cannot be changed after creation)
- Homogeneous elements (all elements same data type)
- Index-based access (0 to length-1)
- Contiguous memory allocation
- Can store primitives or objects
- Implements Cloneable and Serializable interfaces

2. How do you declare and initialize arrays in Java?

Different ways to declare and initialize arrays:
Declaration: int[] arr; or int arr[];
Initialization:
- int[] arr = new int[5]; // with size
- int[] arr = {1, 2, 3, 4, 5}; // direct initialization
- int[] arr = new int[]{1, 2, 3}; // anonymous array

3. What is the difference between array declaration types: int[] arr vs int arr[]?

Both declarations are valid and equivalent in Java:
int[] arr - Preferred style, clearly indicates arr is an array of integers
int arr[] - C-style declaration, allowed for familiarity
For multiple variables: int[] arr1, arr2; (both arrays) vs int arr1[], arr2; (arr1 is array, arr2 is int)

4. What is the default value of array elements in Java?

When arrays are created, elements are automatically initialized with default values:
- byte, short, int, long: 0
- float, double: 0.0
- char: '\u0000' (null character)
- boolean: false
- Object references: null

5. What are multidimensional arrays and how are they stored?

Multidimensional arrays are arrays of arrays:
int[][] matrix = new int[3][4]; // 3 rows, 4 columns
In memory, they're stored as:
- Array of references (first dimension)
- Each reference points to another array (second dimension)
Java supports jagged arrays where inner arrays can have different lengths

6. What are jagged arrays in Java?

Jagged arrays are multidimensional arrays where inner arrays have different lengths:
int[][] jagged = new int[3][];
jagged[0] = new int[2]; // first row has 2 elements
jagged[1] = new int[3]; // second row has 3 elements
jagged[2] = new int[1]; // third row has 1 element

This provides memory efficiency when rows have varying data sizes.

7. How do you copy arrays in Java?

Multiple ways to copy arrays:
Manual copying: Using for loop
System.arraycopy(): System.arraycopy(src, srcPos, dest, destPos, length);
Arrays.copyOf(): int[] copy = Arrays.copyOf(original, newLength);
clone(): int[] copy = original.clone();
Object.clone() creates shallow copy for object arrays

8. What is the difference between shallow copy and deep copy in arrays?

Shallow copy: Copies references to objects, both arrays point to same objects
Deep copy: Creates new copies of all objects, completely independent
Example with Object array:
- clone() and Arrays.copyOf() create shallow copies
- For deep copy, manually create new objects for each element

9. What are anonymous arrays in Java?

Anonymous arrays are arrays without name, created and initialized in a single statement:
printArray(new int[]{1, 2, 3, 4, 5});
They are useful for:
- Passing arrays to methods without declaring variables
- One-time use scenarios
- Cannot specify size in anonymous arrays: new int[3]{1,2,3} is invalid

10. How does array passing work in Java methods?

Arrays are passed by reference value in Java:
- The reference to the array is passed by value
- Modifications to array elements are reflected in original array
- Reassigning the parameter doesn't affect the original reference
Example: void modify(int[] arr) { arr[0] = 100; } changes original array

11. What is ArrayIndexOutOfBoundsException and when does it occur?

ArrayIndexOutOfBoundsException is a runtime exception thrown when:
- Accessing array with negative index: arr[-1]
- Accessing array with index >= length: arr[arr.length]
- In loops: for(int i=0; i<=arr.length; i++) (should be i < arr.length)

12. What are the main methods available in java.util.Arrays class?

Key utility methods in Arrays class:
- Arrays.sort() - sorts array
- Arrays.binarySearch() - searches sorted array
- Arrays.equals() - compares arrays
- Arrays.fill() - fills array with value
- Arrays.copyOf() - copies array
- Arrays.toString() - converts to string
- Arrays.asList() - converts to List

13. How does Arrays.sort() work for primitive and object arrays?

For primitive arrays: Uses Dual-Pivot Quicksort algorithm (O(n log n) average)
For object arrays: Uses TimSort (adaptive, stable merge sort)
Object arrays require elements to implement Comparable interface or use Comparator
Arrays.sort(primitiveArr);
Arrays.sort(objectArr, comparator);

14. What is the difference between Arrays.equals() and == for arrays?

== operator: Compares references (memory addresses)
Arrays.equals(): Compares content of arrays element by element
Example:
int[] a = {1,2,3}; int[] b = {1,2,3};
a == b
// false (different objects)
Arrays.equals(a, b) // true (same content)

15. How do you convert an array to ArrayList?

Using Arrays.asList() method:
String[] array = {"a", "b", "c"};
List<String> list = Arrays.asList(array);

Important: The returned list is fixed-size and backed by the original array
For modifiable list: new ArrayList<>(Arrays.asList(array));

16. What are the advantages and disadvantages of arrays?

Advantages:
- Fast random access (O(1) time complexity)
- Memory efficient (contiguous allocation)
- Cache friendly
- Simple to use
Disadvantages:
- Fixed size
- Expensive insertions/deletions (need shifting)
- Cannot store different data types
- Wasted memory if oversized

17. How do you resize an array in Java?

Arrays have fixed size, but you can create a new larger array and copy elements:
int[] resizeArray(int[] original, int newSize) {
int[] newArray = new int[newSize];
System.arraycopy(original, 0, newArray, 0, Math.min(original.length, newSize));
return newArray;
}

Or use Arrays.copyOf(original, newSize)

18. What is the time complexity of common array operations?

Access: O(1) - direct index access
Search: O(n) - linear search, O(log n) if sorted with binary search
Insertion at end: O(1) if space available, O(n) if resizing needed
Insertion at beginning/middle: O(n) - requires shifting
Deletion: O(n) - requires shifting
Sorting: O(n log n) for efficient algorithms

19. How do you find the length of an array?

Using the length field (not method):
int[] arr = {1, 2, 3, 4, 5};
int size = arr.length;

For multidimensional arrays:
int[][] matrix = new int[3][4];
int rows = matrix.length; // 3
int cols = matrix[0].length; // 4

20. What are the common array algorithms every Java developer should know?

Essential array algorithms:
- Linear search - find element in unsorted array
- Binary search - find element in sorted array
- Reverse array - swap elements from ends to middle
- Find min/max - iterate and compare
- Remove duplicates - using Set or in-place
- Rotate array - using reversal or temporary array
- Merge sorted arrays - two-pointer technique

Previous Java Interview Questions Next