Chapter 10 Beginner 55 Questions

Practice Questions — Arrays in Java

← Back to Notes
8 Easy
11 Medium
11 Hard

Topic-Specific Questions

Question 1
Easy
What is the output?
int[] arr = {10, 20, 30, 40, 50};
System.out.println(arr[0]);
System.out.println(arr[4]);
System.out.println(arr.length);
Arrays are 0-indexed. length is a property.
10
50
5
Question 2
Easy
What is the output?
int[] arr = new int[4];
System.out.println(arr[0]);
System.out.println(arr[3]);
Default value for int arrays is 0.
0
0
Question 3
Easy
What is the output?
String[] names = new String[3];
System.out.println(names[0]);
Default value for reference type arrays is null.
null
Question 4
Easy
What is the output?
int[] arr = {5, 10, 15};
arr[1] = 99;
for (int n : arr) {
    System.out.print(n + " ");
}
We modify index 1 from 10 to 99.
5 99 15
Question 5
Medium
What is the output?
int[] a = {1, 2, 3};
int[] b = a;
b[0] = 99;
System.out.println(a[0]);
b = a copies the reference, not the data.
99
Question 6
Medium
What is the output?
int[] arr = {1, 2, 3};
System.out.println(arr == arr);
int[] arr2 = {1, 2, 3};
System.out.println(arr == arr2);
== compares references, not content.
true
false
Question 7
Medium
What is the output?
import java.util.Arrays;
int[] arr = {5, 2, 8, 1, 9};
Arrays.sort(arr);
System.out.println(Arrays.toString(arr));
Arrays.sort() sorts in ascending order in-place.
[1, 2, 5, 8, 9]
Question 8
Medium
What is the output?
int[][] matrix = {{1, 2}, {3, 4}, {5, 6}};
System.out.println(matrix.length);
System.out.println(matrix[0].length);
System.out.println(matrix[2][1]);
matrix.length = rows. matrix[i].length = columns in row i.
3
2
6
Question 9
Hard
What is the output?
import java.util.Arrays;
int[] arr = {3, 1, 4, 1, 5};
int[] copy = Arrays.copyOf(arr, 3);
arr[0] = 99;
System.out.println(Arrays.toString(copy));
copyOf creates an independent copy. Changes to arr do not affect copy.
[3, 1, 4]
Question 10
Hard
What is the output?
import java.util.Arrays;
int[] arr = {10, 20, 30, 40, 50};
Arrays.sort(arr);
int idx = Arrays.binarySearch(arr, 30);
System.out.println(idx);
After sorting: {10, 20, 30, 40, 50}. Find the index of 30.
2
Question 11
Hard
What is the output?
int[][] jagged = new int[3][];
jagged[0] = new int[]{1};
jagged[1] = new int[]{2, 3};
jagged[2] = new int[]{4, 5, 6};
int sum = 0;
for (int[] row : jagged) {
    for (int val : row) {
        sum += val;
    }
}
System.out.println(sum);
Sum all elements across all rows of different lengths.
21
Question 12
Medium
Why is arr.length a property (no parentheses) while String's length() is a method (with parentheses)?
Think about the difference between a field and a method.
Arrays have a public final field called length that is set when the array is created and never changes. It is accessed as a field (no parentheses). Strings use a length() method because String is a class with encapsulated internal state. The distinction is a Java design decision: arrays are a special construct in the language, not a regular class.
Question 13
Hard
Explain the difference between Arrays.copyOf() and assigning one array to another (arr2 = arr1).
Think about references vs actual data.
arr2 = arr1 copies the reference, making both variables point to the same underlying array object. Changes through either variable affect the same data. Arrays.copyOf(arr1, arr1.length) creates a new array object with the same values but independent memory. Changes to one do not affect the other.
Question 14
Easy
What is the output?
boolean[] flags = new boolean[3];
System.out.println(flags[0]);
System.out.println(flags[2]);
Default value for boolean arrays is false.
false
false
Question 15
Medium
What is the output?
int[] arr = {10, 20, 30, 40};
int sum = 0;
for (int i = 0; i < arr.length; i += 2) {
    sum += arr[i];
}
System.out.println(sum);
i takes values 0 and 2 (step by 2). Access arr[0] and arr[2].
40
Question 16
Hard
What is the output?
import java.util.Arrays;
int[] a = {1, 2, 3};
int[] b = a.clone();
b[0] = 99;
System.out.println(Arrays.toString(a));
System.out.println(Arrays.toString(b));
clone() creates an independent copy.
[1, 2, 3]
[99, 2, 3]
Question 17
Hard
What is the output?
import java.util.Arrays;
int[] arr = {5, 3, 8, 1, 2};
Arrays.sort(arr, 1, 4);
System.out.println(Arrays.toString(arr));
sort(arr, fromIndex, toIndex) sorts only the range [1, 4).
[5, 1, 3, 8, 2]

Mixed & Application Questions

Question 1
Easy
Write a program that creates an array of 5 integers, reads values from the user, and prints their sum and average.
Use a for loop to read and sum.
import java.util.Scanner;

public class ArraySum {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int[] arr = new int[5];
        System.out.println("Enter 5 numbers:");
        int sum = 0;
        for (int i = 0; i < 5; i++) {
            arr[i] = sc.nextInt();
            sum += arr[i];
        }
        System.out.println("Sum: " + sum);
        System.out.println("Average: " + (double) sum / 5);
        sc.close();
    }
}
Question 2
Easy
What is the output?
int[] arr = {10, 20, 30};
for (int i = arr.length - 1; i >= 0; i--) {
    System.out.print(arr[i] + " ");
}
Iterating from the last index to 0 prints in reverse.
30 20 10
Question 3
Medium
What is the output?
int[] arr = {5, 3, 8, 1, 9, 2};
int min = arr[0];
for (int i = 1; i < arr.length; i++) {
    if (arr[i] < min) {
        min = arr[i];
    }
}
System.out.println("Min: " + min);
Track the smallest value seen so far.
Min: 1
Question 4
Medium
Write a method that takes an int array and returns a new array with elements in reverse order. Do not modify the original.
Create a new array. Copy elements from end to start.
import java.util.Arrays;

public class ReverseArray {
    public static int[] reverse(int[] arr) {
        int[] result = new int[arr.length];
        for (int i = 0; i < arr.length; i++) {
            result[i] = arr[arr.length - 1 - i];
        }
        return result;
    }

    public static void main(String[] args) {
        int[] nums = {1, 2, 3, 4, 5};
        int[] rev = reverse(nums);
        System.out.println(Arrays.toString(rev));
        System.out.println(Arrays.toString(nums)); // unchanged
    }
}
Question 5
Medium
What is the output?
import java.util.Arrays;
int[] arr = new int[5];
Arrays.fill(arr, 3);
arr[2] = 7;
System.out.println(Arrays.toString(arr));
fill sets all to 3, then we override index 2.
[3, 3, 7, 3, 3]
Question 6
Hard
What is the output?
int[][] m = {{1, 2, 3}, {4, 5, 6}};
int[][] t = new int[3][2];
for (int i = 0; i < 2; i++) {
    for (int j = 0; j < 3; j++) {
        t[j][i] = m[i][j];
    }
}
System.out.println(t[0][0] + " " + t[0][1]);
System.out.println(t[1][0] + " " + t[1][1]);
System.out.println(t[2][0] + " " + t[2][1]);
This is a matrix transpose: t[j][i] = m[i][j].
1 4
2 5
3 6
Question 7
Hard
What is the output?
import java.util.Arrays;
int[] arr = {3, 1, 4, 1, 5, 9, 2, 6};
Arrays.sort(arr);
int result = Arrays.binarySearch(arr, 7);
System.out.println(result);
7 is not in the array. binarySearch returns a negative value.
A negative value (specifically -8)
Question 8
Hard
What is the output?
int[] arr = {1, 2, 3, 4, 5};
for (int n : arr) {
    n = n * 10;
}
System.out.println(arr[0] + " " + arr[4]);
for-each variable is a copy for primitive arrays.
1 5
Question 9
Hard
Write a program that reads a 3x3 matrix from the user and prints the sum of each row, each column, and both diagonals.
Use nested loops. Column sum: iterate rows for a fixed column.
import java.util.Scanner;

public class MatrixSums {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int[][] m = new int[3][3];
        System.out.println("Enter 3x3 matrix:");
        for (int i = 0; i < 3; i++)
            for (int j = 0; j < 3; j++)
                m[i][j] = sc.nextInt();

        for (int i = 0; i < 3; i++) {
            int rowSum = 0;
            for (int j = 0; j < 3; j++) rowSum += m[i][j];
            System.out.println("Row " + i + " sum: " + rowSum);
        }
        for (int j = 0; j < 3; j++) {
            int colSum = 0;
            for (int i = 0; i < 3; i++) colSum += m[i][j];
            System.out.println("Col " + j + " sum: " + colSum);
        }
        int d1 = 0, d2 = 0;
        for (int i = 0; i < 3; i++) {
            d1 += m[i][i];
            d2 += m[i][2 - i];
        }
        System.out.println("Main diagonal: " + d1);
        System.out.println("Anti diagonal: " + d2);
        sc.close();
    }
}
Question 10
Easy
What is the output?
int[] arr = {3, 6, 9};
System.out.println(arr[arr.length - 1]);
arr.length is 3. arr[3-1] = arr[2].
9
Question 11
Medium
What is the output?
int[] arr = {1, 2, 3, 4, 5};
int[] reversed = new int[arr.length];
for (int i = 0; i < arr.length; i++) {
    reversed[i] = arr[arr.length - 1 - i];
}
System.out.print(reversed[0] + " " + reversed[4]);
reversed[0] = arr[4], reversed[4] = arr[0].
5 1
Question 12
Medium
Write a method that takes an int array and returns true if the array is sorted in ascending order, false otherwise.
Check if each element is <= the next element.
public static boolean isSorted(int[] arr) {
    for (int i = 0; i < arr.length - 1; i++) {
        if (arr[i] > arr[i + 1]) {
            return false;
        }
    }
    return true;
}
Question 13
Hard
What is the output?
import java.util.Arrays;
int[] arr = {1, 2, 3, 4, 5};
int[] bigger = Arrays.copyOf(arr, 8);
System.out.println(Arrays.toString(bigger));
copyOf with a larger length pads with default values.
[1, 2, 3, 4, 5, 0, 0, 0]

Multiple Choice Questions

MCQ 1
What is the index of the first element in a Java array?
  • A. 1
  • B. 0
  • C. -1
  • D. Depends on the array
Answer: B
B is correct. Java arrays are zero-indexed. The first element is at index 0.
MCQ 2
What is the default value of elements in a new int array?
  • A. null
  • B. -1
  • C. 0
  • D. undefined
Answer: C
C is correct. Default values: 0 for int, 0.0 for double, false for boolean, null for reference types.
MCQ 3
Which property gives the number of elements in an array?
  • A. arr.size()
  • B. arr.length()
  • C. arr.length
  • D. arr.count
Answer: C
C is correct. length is a field (no parentheses) for arrays. length() is a method for Strings. size() is a method for Collections.
MCQ 4
What exception is thrown when accessing an invalid array index?
  • A. IndexOutOfBoundsException
  • B. ArrayIndexOutOfBoundsException
  • C. NullPointerException
  • D. IllegalArgumentException
Answer: B
B is correct. ArrayIndexOutOfBoundsException is thrown when accessing an index < 0 or >= array.length.
MCQ 5
Which method from the Arrays class sorts an array?
  • A. Arrays.order()
  • B. Arrays.arrange()
  • C. Arrays.sort()
  • D. Arrays.sorted()
Answer: C
C is correct. Arrays.sort() sorts the array in ascending order in-place.
MCQ 6
What does Arrays.toString(arr) return for int[] arr = {1, 2, 3}?
  • A. [1, 2, 3]
  • B. {1, 2, 3}
  • C. 1 2 3
  • D. [I@6d06d69c
Answer: A
A is correct. Arrays.toString() returns a string in the format [element1, element2, ...]. Option D is what System.out.println(arr) prints without Arrays.toString().
MCQ 7
What is a jagged array?
  • A. An array with null elements
  • B. A 2D array where each row can have a different number of columns
  • C. An array that is not sorted
  • D. An array with negative indices
Answer: B
B is correct. A jagged array is a 2D array where rows have varying lengths. In Java, this is possible because a 2D array is an array of references to independent 1D arrays.
MCQ 8
What happens when you pass an array to a method in Java?
  • A. A copy of the array is passed
  • B. The reference (memory address) is passed
  • C. Only the first element is passed
  • D. It depends on the array size
Answer: B
B is correct. Java passes the array reference (pass by value of the reference). The method operates on the same underlying array, so modifications affect the original.
MCQ 9
What does Arrays.binarySearch() require?
  • A. The array must be in descending order
  • B. The array must be sorted in ascending order
  • C. The array can be unsorted
  • D. The array must contain unique elements
Answer: B
B is correct. binarySearch() requires the array to be sorted in ascending order. Using it on an unsorted array produces undefined results.
MCQ 10
What is the output?
int[] a = {1}; int[] b = {1}; System.out.println(a.equals(b));
  • A. true
  • B. false
  • C. Error
  • D. 1
Answer: B
B is correct. Arrays inherit equals() from Object, which compares references (same as ==). Two different array objects are not equal by reference. Use Arrays.equals(a, b) for content comparison.
MCQ 11
What is the time complexity of Arrays.sort() for primitive arrays?
  • A. O(n)
  • B. O(n log n)
  • C. O(n^2)
  • D. O(log n)
Answer: B
B is correct. Arrays.sort() uses dual-pivot Quicksort for primitives with O(n log n) average time complexity. For object arrays, it uses TimSort (also O(n log n)).
MCQ 12
What does Arrays.copyOfRange(arr, 2, 5) return for arr = {10, 20, 30, 40, 50, 60}?
  • A. [30, 40, 50]
  • B. [20, 30, 40, 50]
  • C. [30, 40, 50, 60]
  • D. [20, 30, 40]
Answer: A
A is correct. copyOfRange(arr, 2, 5) copies indices 2, 3, 4 (from=inclusive, to=exclusive). Elements: arr[2]=30, arr[3]=40, arr[4]=50.
MCQ 13
Can arrays store elements of different types in Java?
  • A. Yes, all arrays accept any type
  • B. Yes, if declared as Object[]
  • C. No, arrays are always homogeneous
  • D. Only if using generics
Answer: B
B is correct. An Object[] array can store any type because all classes inherit from Object. However, the array itself is typed as Object[], and you need casting when retrieving elements. Primitive arrays (int[], double[]) are strictly homogeneous.
MCQ 14
How do you create an independent copy of an array?
  • A. int[] copy = original;
  • B. int[] copy = Arrays.copyOf(original, original.length);
  • C. int[] copy = new int[original];
  • D. int[] copy = original.copy();
Answer: B
B is correct. Arrays.copyOf() creates a new array with copied values. Option A copies the reference (not independent). Option C is invalid syntax. Option D: arrays do not have a copy() method (they have clone()).
MCQ 15
What is the valid index range for an array of length 10?
  • A. 1 to 10
  • B. 0 to 10
  • C. 0 to 9
  • D. 1 to 9
Answer: C
C is correct. Arrays are 0-indexed. An array of length 10 has valid indices 0 through 9.
MCQ 16
Which method prints a 2D array in readable format?
  • A. Arrays.toString()
  • B. Arrays.deepToString()
  • C. Arrays.print()
  • D. System.out.println()
Answer: B
B is correct. Arrays.deepToString() handles multidimensional arrays, printing them as [[row1], [row2], ...]. Arrays.toString() only works for 1D arrays.
MCQ 17
What is the output?
int[] arr = {}; System.out.println(arr.length);
  • A. 0
  • B. null
  • C. Error
  • D. -1
Answer: A
A is correct. An empty array {} is a valid array with length 0. It is not null; it is an array object that contains no elements.

Coding Challenges

Challenge 1: Find Second Largest Element

Easy
Write a program that finds the second largest element in an array without sorting.
Sample Input
Array: {12, 35, 1, 10, 34, 1}
Sample Output
Second largest: 34
Track both the largest and second largest in a single pass.
public class SecondLargest {
    public static void main(String[] args) {
        int[] arr = {12, 35, 1, 10, 34, 1};
        int first = Integer.MIN_VALUE, second = Integer.MIN_VALUE;
        for (int n : arr) {
            if (n > first) {
                second = first;
                first = n;
            } else if (n > second && n != first) {
                second = n;
            }
        }
        System.out.println("Second largest: " + second);
    }
}

Challenge 2: Reverse Array In-Place

Easy
Reverse an array in-place using two pointers (without creating a new array).
Sample Input
Array: {1, 2, 3, 4, 5}
Sample Output
Reversed: [5, 4, 3, 2, 1]
Use two pointers: one at start, one at end. Swap and move inward.
import java.util.Arrays;

public class ReverseInPlace {
    public static void main(String[] args) {
        int[] arr = {1, 2, 3, 4, 5};
        int left = 0, right = arr.length - 1;
        while (left < right) {
            int temp = arr[left];
            arr[left] = arr[right];
            arr[right] = temp;
            left++;
            right--;
        }
        System.out.println("Reversed: " + Arrays.toString(arr));
    }
}

Challenge 3: Count Frequency of Each Element

Medium
Given an array of integers, count and print the frequency of each distinct element.
Sample Input
Array: {3, 5, 3, 2, 5, 5, 1, 2}
Sample Output
3 appears 2 times 5 appears 3 times 2 appears 2 times 1 appears 1 times
Use a boolean visited array to avoid counting duplicates twice.
public class Frequency {
    public static void main(String[] args) {
        int[] arr = {3, 5, 3, 2, 5, 5, 1, 2};
        boolean[] visited = new boolean[arr.length];
        for (int i = 0; i < arr.length; i++) {
            if (visited[i]) continue;
            int count = 1;
            for (int j = i + 1; j < arr.length; j++) {
                if (arr[i] == arr[j]) {
                    count++;
                    visited[j] = true;
                }
            }
            System.out.println(arr[i] + " appears " + count + " times");
        }
    }
}

Challenge 4: Merge Two Sorted Arrays

Medium
Given two sorted arrays, merge them into a single sorted array without using Arrays.sort().
Sample Input
a = {1, 3, 5, 7}, b = {2, 4, 6, 8}
Sample Output
Merged: [1, 2, 3, 4, 5, 6, 7, 8]
Use two pointers, one for each array. Compare and pick the smaller element.
import java.util.Arrays;

public class MergeSorted {
    public static void main(String[] args) {
        int[] a = {1, 3, 5, 7}, b = {2, 4, 6, 8};
        int[] merged = new int[a.length + b.length];
        int i = 0, j = 0, k = 0;
        while (i < a.length && j < b.length) {
            if (a[i] <= b[j]) merged[k++] = a[i++];
            else merged[k++] = b[j++];
        }
        while (i < a.length) merged[k++] = a[i++];
        while (j < b.length) merged[k++] = b[j++];
        System.out.println("Merged: " + Arrays.toString(merged));
    }
}

Challenge 5: Rotate Array by K Positions

Medium
Rotate an array to the left by K positions. Example: {1,2,3,4,5} rotated left by 2 becomes {3,4,5,1,2}.
Sample Input
Array: {1, 2, 3, 4, 5}, K = 2
Sample Output
Rotated: [3, 4, 5, 1, 2]
Use the reversal algorithm: reverse first K, reverse rest, reverse all.
import java.util.Arrays;

public class RotateArray {
    static void reverse(int[] arr, int start, int end) {
        while (start < end) {
            int temp = arr[start];
            arr[start] = arr[end];
            arr[end] = temp;
            start++;
            end--;
        }
    }

    public static void main(String[] args) {
        int[] arr = {1, 2, 3, 4, 5};
        int k = 2;
        k = k % arr.length;
        reverse(arr, 0, k - 1);
        reverse(arr, k, arr.length - 1);
        reverse(arr, 0, arr.length - 1);
        System.out.println("Rotated: " + Arrays.toString(arr));
    }
}

Challenge 6: Matrix Addition

Medium
Read two 2x3 matrices from the user and print their sum matrix.
Sample Input
Matrix A: {{1,2,3},{4,5,6}}, Matrix B: {{7,8,9},{10,11,12}}
Sample Output
Sum: {{8,10,12},{14,16,18}}
Add corresponding elements: C[i][j] = A[i][j] + B[i][j].
import java.util.Arrays;

public class MatrixAdd {
    public static void main(String[] args) {
        int[][] a = {{1,2,3},{4,5,6}};
        int[][] b = {{7,8,9},{10,11,12}};
        int[][] sum = new int[2][3];
        for (int i = 0; i < 2; i++) {
            for (int j = 0; j < 3; j++) {
                sum[i][j] = a[i][j] + b[i][j];
            }
        }
        System.out.println("Sum:");
        for (int[] row : sum) System.out.println(Arrays.toString(row));
    }
}

Challenge 7: Find Duplicate Elements

Hard
Given an array, find and print all duplicate elements (elements that appear more than once).
Sample Input
Array: {4, 2, 7, 2, 4, 9, 7, 1}
Sample Output
Duplicates: 2, 7, 4
Use nested loops or sorting. Print each duplicate only once.
import java.util.Arrays;

public class FindDuplicates {
    public static void main(String[] args) {
        int[] arr = {4, 2, 7, 2, 4, 9, 7, 1};
        int[] sorted = Arrays.copyOf(arr, arr.length);
        Arrays.sort(sorted);
        System.out.print("Duplicates: ");
        for (int i = 1; i < sorted.length; i++) {
            if (sorted[i] == sorted[i - 1]) {
                if (i == 1 || sorted[i] != sorted[i - 2]) {
                    System.out.print(sorted[i] + " ");
                }
            }
        }
        System.out.println();
    }
}

Challenge 8: Spiral Matrix Traversal

Hard
Given an m x n matrix, print its elements in spiral order (right, down, left, up, repeat).
Sample Input
Matrix: {{1,2,3},{4,5,6},{7,8,9}}
Sample Output
1 2 3 6 9 8 7 4 5
Use four boundary variables: top, bottom, left, right. Shrink after each direction.
public class SpiralTraversal {
    public static void main(String[] args) {
        int[][] matrix = {{1,2,3},{4,5,6},{7,8,9}};
        int top = 0, bottom = matrix.length - 1;
        int left = 0, right = matrix[0].length - 1;
        while (top <= bottom && left <= right) {
            for (int i = left; i <= right; i++) System.out.print(matrix[top][i] + " ");
            top++;
            for (int i = top; i <= bottom; i++) System.out.print(matrix[i][right] + " ");
            right--;
            if (top <= bottom) {
                for (int i = right; i >= left; i--) System.out.print(matrix[bottom][i] + " ");
                bottom--;
            }
            if (left <= right) {
                for (int i = bottom; i >= top; i--) System.out.print(matrix[i][left] + " ");
                left++;
            }
        }
        System.out.println();
    }
}

Need to Review the Concepts?

Go back to the detailed notes for this chapter.

Read Chapter Notes

Want to learn Java with a live mentor?

Explore our Java Masterclass