Declare and Initialize an Array

public class ArrayInitialization {
    public static void main(String[] args) {
        int[] numbers = {10, 20, 30, 40, 50};
        // array size is implicitly 5; indices run 0..length-1
    }
}

The array is a fixed-size, index-based data structure where the indices range from 0 to length - 1. The array reference is stored on the stack and points to the array object in heap memory.

Analogy: Think of an array as a row of numbered lockers. Each locker has a unique index starting from 0, and the program accesses each element using its corresponding index.


public class PrintArrayElements {
    public static void main(String[] args) {
        int[] numbers = {10, 20, 30, 40, 50};
        for (int i = 0; i < numbers.length; i++) {
            System.out.println(numbers[i]);
        }
    }
}

You can also print array elements using an enhanced for-loop:

Advertisement
for (int num : numbers) {
    System.out.println(num);
}

For quick debugging, use:

Arrays.toString(numbers);

Sum of Array Elements

public class SumOfArrayElements {
    public static void main(String[] args) {
        int[] numbers = {10, 20, 30, 40, 50};
        int sum = 0;
        for (int i = 0; i < numbers.length; i++) {
            sum = sum + numbers[i];
        }
        System.out.println("Sum of array elements: " + sum);
    }
}

Enhanced for-loop version:

int sum = 0;
for (int num : numbers) {
    sum += num;
}

Logic

  • Initialize a variable with 0.
  • Traverse the array.
  • Add each element to the accumulator.
  • Print the final sum.

Time Complexity: O(n)

Space Complexity: O(1)


Average of an Array

public class AverageOfArray {
    public static void main(String[] args) {
        int[] numbers = {10, 20, 30, 40, 50};
        int sum = 0;
        for (int num : numbers) {
            sum += num;
        }
        double average = (double) sum / numbers.length;
        System.out.println("Average: " + average);
    }
}

Important: Cast the sum to double before division.

(double) sum / numbers.length

This prevents integer division from truncating the decimal value.


Second Largest Element

public class SecondLargestElement {
    public static void main(String[] args) {
        int[] numbers = {10, 45, 23, 89, 67};
        int largest = numbers[0];
        int secondLargest = Integer.MIN_VALUE;
        for (int i = 1; i < numbers.length; i++) {
            if (numbers[i] > largest) {
                secondLargest = largest;
                largest = numbers[i];
            } else if (numbers[i] > secondLargest && numbers[i] != largest) {
                secondLargest = numbers[i];
            }
        }
        System.out.println("Second Largest Element: " + secondLargest);
    }
}

Logic

  • Maintain two variables:
    • largest
    • secondLargest
  • When a larger value is found:
    • Move the current largest value into secondLargest.
    • Update largest.
  • Otherwise, update secondLargest only if the value lies between the two.

This approach completes in a single pass without sorting.

Time Complexity: O(n)


Second Smallest Element

Track:

  • smallest
  • secondSmallest

Initialize secondSmallest using Integer.MAX_VALUE.

When a smaller value is found:

  • Move the existing smallest value into secondSmallest.
  • Update smallest.

Otherwise, update secondSmallest only if the current value is smaller than it and different from the smallest value.

Time Complexity: O(n)


Difference Between Maximum and Minimum

public class DifferenceMaxMin {
    public static void main(String[] args) {
        int[] numbers = {10, 45, 23, 89, 67};
        int max = numbers[0], min = numbers[0];
        for (int num : numbers) {
            if (num > max) max = num;
            if (num < min) min = num;
        }
        System.out.println("Difference: " + (max - min));
    }
}

Find both the maximum and minimum values during a single traversal, then calculate:

Difference = Maximum − Minimum

Time Complexity: O(n)

Space Complexity: O(1)


Frequently Asked Questions

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

Maintain two variables: largest and secondLargest. During a single traversal, update them whenever a larger value is found. This avoids sorting and runs in O(n) time.


Why should you cast to double when calculating the average?

Without casting, integer division removes the decimal portion. Casting the sum to double before division returns the correct average.


What is the time complexity of these programs?

Most of these array programs execute in:

  • Time Complexity: O(n)
  • Space Complexity: O(1)

How can you print an array quickly?

Use:

Arrays.toString(array)

or iterate using an enhanced for-loop.


Why does array indexing start from 0?

Java arrays use zero-based indexing, where valid indices range from 0 to length - 1. The array reference points to the first element, and every subsequent element is accessed using its offset from index 0.