Java Array Operations and Memory Management

Array Fundamentals

An array is a fixed-size container designed to hold multiple values of the identical data type. Once created, its length cannot change.

Declaration Syntax

Arrays can be declared using two distinct formats:

DataType[] arrayName; // Preferred format
DataType arrayName[]; // Alternative format

Examples:

double[] measurements;
String[] names;

Array Initialization

Dynamic Initialization

Dynamic initialization specifies the array's capacity. The system automatically assigns default values (e.g., 0 for integers, null for objects) to each position.

Syntax:

DataType[] arrayName = new DataType[length];

Example and memory address output:

public class DynamicArrayDemo {
    public static void main(String[] args) {
        double[] readings = new double[5];
        // Prints the memory address: [D@someHexValue
        System.out.println(readings);

        float[] floats = new float[3];
        // Prints the memory address: [F@someHexValue
        System.out.println(floats);
    }
}

Static Initialization

Static initialization directly assigns elements to the array upon creation. The system determines the length based on the provided elements.

Syntax:

// Full format
DataType[] arrayName = new DataType[]{val1, val2, val3};
// Shorthand format
DataType[] arrayName = {val1, val2, val3};

Example:

public class StaticArrayDemo {
    public static void main(String[] args) {
        char[] vowels = new char[]{'a', 'e', 'i', 'o', 'u'};
        System.out.println(vowels[0]);

        int[] digits = {1, 2, 3, 4, 5};
        System.out.println(digits[2]);
    }
}

Element Access

Each element in an array is automatically assigned an index starting from 0. Elements are accessed or modified using this index.

public class ElementAccessDemo {
    public static void main(String[] args) {
        int[] data = new int[4];
        // Accessing default values
        System.out.println(data[0]); // Outputs 0

        // Modifying elements
        data[0] = 100;
        data[1] = 200;
        System.out.println(data[0]); // Outputs 100
    }
}

JVM Memory Allocation

The Java Virtual Machine divides its memory into several regions:

Memory AreaPurpose
RegistersCPU-specific, not directly controlled by developers.
Native Method StackUsed for OS-level native method execution.
Method AreaStores compiled class structures and static variables.
Heap MemoryStores dynamically created objects and arrays (those instantiated with the new keyword).
Stack MemoryManages method execution and stores local variables, including array references.

When an array is created, the reference is stored in the stack, while the actual elements reside in the heap. Multiple variables can point to the same heap memory location.

Common Array Exceptions

ArrayIndexOutOfBoundsException

Occurs when attempting to access an index outside the valid range (0 to length-1).

int[] values = new int[2];
// System.out.println(values[5]); // Throws ArrayIndexOutOfBoundsException

NullPointerException

Occurs when an array reference is set to null, and an attempt is made to access its elements.

int[] items = new int[3];
items = null;
// System.out.println(items[0]); // Throws NullPointerException

Core Array Algorithms

Traversal

Iterating over all elements in an array is typically achieved using a loop.

public class TraversalDemo {
    public static void main(String[] args) {
        int[] sequence = {5, 10, 15, 20, 25};
        for (int i = 0; i < sequence.length; i++) {
            System.out.println(sequence[i]);
        }
    }
}

Finding the Maximum Value

To find the largest element, initialize a variable with the first element, then iterate to compare and update it.

public class MaxValueFinder {
    public static void main(String[] args) {
        int[] quantities = {34, 89, 12, 76, 51};
        int peak = quantities[0];
        for (int i = 1; i < quantities.length; i++) {
            if (quantities[i] > peak) {
                peak = quantities[i];
            }
        }
        System.out.println("Maximum: " + peak);
    }
}

Summation with User Input

Collect inputs dynamically, store them in an array, and calculate the cumulative sum.

import java.util.Scanner;

public class SummationApp {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        int[] inputs = new int[5];
        int aggregate = 0;

        for (int i = 0; i < inputs.length; i++) {
            System.out.print("Enter value " + (i + 1) + ": ");
            inputs[i] = scanner.nextInt();
        }

        for (int val : inputs) {
            aggregate += val;
        }
        System.out.println("Total Sum: " + aggregate);
    }
}

Linear Search

Locate the index of a specific target value within an array.

import java.util.Scanner;

public class SearchAlgorithm {
    public static void main(String[] args) {
        int[] records = {101, 202, 303, 404, 505};
        Scanner scanner = new Scanner(System.in);
        System.out.print("Enter target to find: ");
        int target = scanner.nextInt();

        int matchIndex = -1;
        for (int i = 0; i < records.length; i++) {
            if (records[i] == target) {
                matchIndex = i;
                break;
            }
        }
        System.out.println("Found at index: " + matchIndex);
    }
}

Filtered Average Calculation

Calculate an average by discarding the highest and lowest values from a set of judge scores.

import java.util.Scanner;

public class ScoreCalculator {
    public static void main(String[] args) {
        int[] ratings = new int[6];
        Scanner scanner = new Scanner(System.in);

        for (int i = 0; i < ratings.length; i++) {
            System.out.print("Enter score from judge " + (i + 1) + ": ");
            int currentScore = scanner.nextInt();
            if (currentScore >= 0 && currentScore <= 100) {
                ratings[i] = currentScore;
            } else {
                System.out.println("Invalid score. Must be between 0 and 100.");
                i--;
            }
        }

        int max = ratings[0];
        int min = ratings[0];
        int sum = 0;

        for (int score : ratings) {
            if (score > max) max = score;
            if (score < min) min = score;
            sum += score;
        }

        int finalAverage = (sum - max - min) / 4;
        System.out.println("Final Score: " + finalAverage);
    }
}

Tags: java Arrays Data Structures JVM Memory

Posted on Sun, 06 Sep 2026 16:32:16 +0000 by mlewis