Java Array Programs for SDET

These are the first array programs in almost every SDET and automation coding round: printing an array, sum, average, minimum and maximum, and the classic second largest. They look easy — which is exactly why interviewers use them to check edge cases: duplicates, negative numbers, empty arrays and integer overflow. Every program below comes from one Java class that was compiled and run; the outputs are real.

Advertisement

Arrays in 30 Seconds

int[] numbers = {10, 45, 23, 89, 67};   // size 5, indexes 0..4
int[] empty = new int[5];                // five zeros
numbers[0];                              // 10
numbers.length;                          // 5 — a field, not a method
numbers[5];                              // ArrayIndexOutOfBoundsException

An array has a fixed size and index-based access. Analogy: a row of numbered lockers — locker 0 is the first; there is no locker 5 in a row of five. Need a size that grows? Use an ArrayList.

for (int i = 0; i < numbers.length; i++) System.out.print(numbers[i] + " ");
// 10 45 23 89 67

for (int n : numbers) System.out.print(n + " ");     // enhanced for — no index needed

System.out.println(Arrays.toString(numbers));        // [10, 45, 23, 89, 67]
System.out.println(numbers);                          // prints something like [I@6d06d69c — not the values

2. Sum of Elements

static long sum(int[] a) {
    long total = 0;                  // long, not int
    for (int x : a) total += x;
    return total;
}
// sum({10, 45, 23, 89, 67}) → 234

Why long? Adding large ints overflows silently:

int sum of {Integer.MAX_VALUE, 1}  → -2147483648   (wrapped around)
long sum of the same               →  2147483648

O(n) time, O(1) space.

3. Average

static double average(int[] a) {
    if (a.length == 0) throw new IllegalArgumentException("empty array");
    return (double) sum(a) / a.length;       // cast BEFORE dividing
}
// average({10, 45, 23, 89, 67}) → 46.8

The classic trap is integer division: 234 / 5 is 46, while 234 / 5.0 is 46.8. And an empty array would divide by zero — handle it explicitly.

4. Minimum, Maximum and Their Difference

static int[] minMax(int[] a) {
    int min = a[0], max = a[0];              // start from a real element, not 0
    for (int x : a) {
        if (x < min) min = x;
        if (x > max) max = x;
    }
    return new int[]{min, max};
}
// {10, 45, 23, 89, 67} → min 10, max 89, difference 79

Starting max at 0 is a common bug: for an all-negative array it would wrongly return 0. One pass finds both values.

5. Second Largest Element ⭐

Track the largest and second-largest distinct values in one pass. When a new largest appears, the old largest becomes second.

static Integer secondLargest(int[] a) {
    Integer first = null, second = null;
    for (int x : a) {
        if (first == null || x > first) { second = first; first = x; }
        else if (x != first && (second == null || x > second)) second = x;
    }
    return second;                           // null when there is no second distinct value
}
Input Result Why it matters
{10, 45, 23, 89, 67} 67 The normal case
{89, 89, 45} 45 Duplicates of the largest must be skipped
{7, 7, 7} null There is no second distinct value
{-5, -2, -9} -5 Works with negatives

Many tutorials initialize secondLargest to Integer.MIN_VALUE — that works for the normal case, but for {7, 7, 7} it returns -2147483648 as if it were a real answer. Using null (or checking the array length first) makes "no answer" explicit. Sorting also works — O(n log n) — but the single pass is O(n) and is what interviewers expect.

6. Second Smallest Element

The mirror image — flip the comparisons:

static Integer secondSmallest(int[] a) {
    Integer first = null, second = null;
    for (int x : a) {
        if (first == null || x < first) { second = first; first = x; }
        else if (x != first && (second == null || x < second)) second = x;
    }
    return second;
}
// {10, 45, 23, 89, 67} → 23

7. The Stream Versions

Arrays.stream(numbers).sum();                        // 234
Arrays.stream(numbers).average().orElse(0);          // 46.8
Arrays.stream(numbers).max().getAsInt();             // 89
Arrays.stream(numbers).boxed().distinct()
      .sorted(Comparator.reverseOrder())
      .skip(1).findFirst().orElse(null);             // 67 — second largest

Streams are concise and worth mentioning, but interviewers usually ask you to write the loop version first — it shows you understand the logic.

8. Access and Update: Element at Index, Replace, Swap, Remove

static int elementAt(int[] a, int index) {
    if (index < 0 || index >= a.length)
        throw new IndexOutOfBoundsException("Index " + index + " out of bounds for length " + a.length);
    return a[index];
}
static void replaceAt(int[] a, int index, int value) { a[index] = value; }
static void swap(int[] a, int i, int j) { int t = a[i]; a[i] = a[j]; a[j] = t; }
static int[] removeAll(int[] a, int value) {            // arrays can't shrink: build a new one
    int count = 0;
    for (int x : a) if (x != value) count++;
    int[] out = new int[count];
    int k = 0;
    for (int x : a) if (x != value) out[k++] = x;
    return out;
}
elementAt(a, 2) → 30
elementAt(a, 5) → Index 5 out of bounds for length 5
after replaceAt(1, 25) and swap(0, 4) → [50, 25, 30, 40, 10]
removeAll([3, 7, 3, 9, 3], 3) → [7, 9]

Reading, replacing and swapping by index are O(1). Removing is different: an array can't shrink, so you count the elements to keep and copy them into a new array (O(n)). Say that out loud in an interview — it's the reason ArrayList exists. Always validate an index from test data before using it, and give a clear message when it's wrong.

The code in this section comes from one class that was compiled and run on Java 21; the outputs are real.

9. Matrix (2D Array) Programs

A matrix is an array of rows: m[row][col]. Every program below is a pair of nested loops; the only thing that changes is which cells you visit.

Transpose

static int[][] transpose(int[][] m) {
    int[][] t = new int[m[0].length][m.length];
    for (int r = 0; r < m.length; r++)
        for (int c = 0; c < m[0].length; c++) t[c][r] = m[r][c];
    return t;
}
transpose([[1,2,3],[4,5,6],[7,8,9]]) → [[1, 4, 7], [2, 5, 8], [3, 6, 9]]
transpose of 2×3 → [[1, 4], [2, 5], [3, 6]]

Create the result as [columns][rows] — a common bug is reusing the original dimensions, which only works for square matrices.

Primary and Secondary Diagonals

static int[] primaryDiagonal(int[][] m)   { int[] d = new int[m.length]; for (int i = 0; i < m.length; i++) d[i] = m[i][i]; return d; }
static int[] secondaryDiagonal(int[][] m) { int n = m.length; int[] d = new int[n]; for (int i = 0; i < n; i++) d[i] = m[i][n - 1 - i]; return d; }
diagonals → primary [1, 5, 9], secondary [3, 5, 7]

Primary: m[i][i]. Secondary: m[i][n - 1 - i]. One loop, O(n) — no need for nested loops with an if. Summing a diagonal is the same loop with a running total.

Upper and Lower Triangular

static boolean isUpperTriangular(int[][] m) {       // zeros below the main diagonal
    for (int r = 1; r < m.length; r++) for (int c = 0; c < r; c++) if (m[r][c] != 0) return false;
    return true;
}
static boolean isLowerTriangular(int[][] m) {       // zeros above the main diagonal
    for (int r = 0; r < m.length; r++) for (int c = r + 1; c < m.length; c++) if (m[r][c] != 0) return false;
    return true;
}
[[1,2,3],[0,4,5],[0,0,6]] → upper-triangular true, lower-triangular false

Identity Matrix

static boolean isIdentity(int[][] m) {
    for (int r = 0; r < m.length; r++)
        for (int c = 0; c < m.length; c++)
            if (m[r][c] != (r == c ? 1 : 0)) return false;
    return true;
}
isIdentity(I3) true, isIdentity([[1,2,3],[4,5,6],[7,8,9]]) false

Multiply Two Matrices

static int[][] multiply(int[][] a, int[][] b) {
    if (a[0].length != b.length) throw new IllegalArgumentException("columns of A must equal rows of B");
    int[][] p = new int[a.length][b[0].length];
    for (int i = 0; i < a.length; i++)
        for (int j = 0; j < b[0].length; j++)
            for (int k = 0; k < b.length; k++) p[i][j] += a[i][k] * b[k][j];
    return p;
}
multiply([[1,2],[3,4]], [[5,6],[7,8]]) → [[19, 22], [43, 50]]
m × I3 equals m: true
1×3 × 1×3 → columns of A must equal rows of B

Multiplication needs columns of A = rows of B; check it first and fail with a clear message. It's O(n³) for square matrices. Multiplying by the identity and getting the original back is a neat self-check — the same idea as a test oracle in automation.

The code in this section comes from one class that was compiled and run on Java 21; the outputs are real.

Row, Column, Total and Diagonal Sums (and Printing a 2D Array)

static long[] rowSums(int[][] m)    { long[] s = new long[m.length]; for (int r = 0; r < m.length; r++) for (int v : m[r]) s[r] += v; return s; }
static long[] columnSums(int[][] m) { long[] s = new long[m[0].length]; for (int[] row : m) for (int c = 0; c < row.length; c++) s[c] += row[c]; return s; }
static long total(int[][] m)        { long t = 0; for (int[] row : m) for (int v : row) t += v; return t; }
static long diagonalSum(int[][] m)  {                  // both diagonals, centre counted once
    int n = m.length; long s = 0;
    for (int i = 0; i < n; i++) { s += m[i][i]; if (i != n - 1 - i) s += m[i][n - 1 - i]; }
    return s;
}
rows [6, 15, 24], columns [12, 15, 18], total 45, both diagonals 25
print 2D → Arrays.deepToString(m) → [[1, 2, 3], [4, 5, 6], [7, 8, 9]]

Row sums loop over each row; column sums flip the loops. When adding both diagonals of an odd-sized matrix, the center cell belongs to both — count it once (1+5+9+3+7 = 25, not 30). Use long for sums and Arrays.deepToString() to print — Arrays.toString() prints the row references.

The code in this section comes from one class that was compiled and run on Java 21; the outputs are real.

Complexity Summary

Program Time Extra space
Print, sum, average, min/max O(n) O(1)
Second largest / smallest (single pass) O(n) O(1)
Second largest by sorting O(n log n) O(1)–O(n)

Where This Shows Up in Automation

The same logic appears in real test code: finding the highest price in a product grid, averaging response times from several API calls, or checking that a "sort by price" result's second item is correct. The difference is that the numbers come from getText() or a JSON response instead of a hard-coded array — see Java for Selenium.

Step through any of these programs line by line in the Java Code Visualizer, then try them under time pressure in the Java Interview Simulator.

From the Interview Room

My automation work has been in Java — Selenium WebDriver scripts with TestNG in Eclipse — and I use OOP concepts such as classes and objects, method overloading, overriding and constructors in page classes and utilities. Small programs like this one are the building blocks of real framework code: looping through data, comparing expected and actual values, and handling edge cases. On Canolog, the many forms and screens across sales, inventory, finance and service are where keeping page details in POM classes and reusable steps in a business library paid off. Always ask about empty arrays and duplicates before writing the code.

📚 Official documentation: dev.java: Learn Java (Oracle) · Java 21 API documentation

Frequently Asked Questions

How do you find the second largest element in an array?

Track the largest and second-largest distinct values in one pass: when a new largest appears, the old largest becomes second; otherwise update second if the value is between them. O(n) time.

What if all elements are the same?

There is no second largest — return null, an empty Optional, or throw an exception, and say which you chose.

Why cast to double when calculating the average?

Without it, integer division drops the decimals: 234 / 5 = 46, not 46.8.

Why use long for the sum?

Summing large int values can overflow and wrap around to a negative number without any error.

How do you print an array quickly?

Arrays.toString(array) — printing the array directly shows a type and hash code, not the values.

Why does indexing start at 0?

The index is an offset from the start of the array, so the first element is at offset 0 and the last at length − 1.