Fading Coder

One Final Commit for the Last Sprint

Home > Tech > Content

Understanding Arrays in Java: Declaration, Memory Allocation, and Practical Examples

Tech 3

What is an Array?

An array is a container that can hold multiple elements of the same data type.

Declaring and Initializing Arrays in Java

Arrays are declareed using the syntax: dataType[] arrayName;.

Initialization can be done in two ways:

  • Static initialization: Assigning values at declaration.
  • Dynamic initialization: Allocating memory at runtime.

The general form for dynamic initialization is: arrayName = new dataType[length];.

Example of dynamic initialization and element assignment:

public class ArrayExample {
    public static void main(String[] args) {
        int[] numbers = new int[7];
        for (int index = 0; index < 7; index++) {
            numbers[index] = index * 2;
            System.out.println(numbers[index]);
        }
    }
}

Memory Storage of Arrays in Java

In Java, arrays are reference types. When an array is declared and initialized, the Java Virtual Machine (JVM) allocates a contiguous block of memory in the heap to store the array elements. The array reference (the variable name) is stored in stack memory and points to the starting address of this heap block.

For example, with int[] arr = new int[5];, arr is a reference stored in the stack. The new int[5] instruction causes the JVM to allocate a contiguous memory block in the heap capable of holding five integers. Each element (initially 0 for integer arrays) is stored sequentially in this block, and arr points to the first element's address.

When accessing an element like arr[2], the JVM calculates the memory adress by offsetting from the starting address by 2 * sizeof(int) (typically 8 bytes, as int is 4 bytes in most Java implementations) and retrieves the value at that location.

For multidimensional arrays, such as a two-dimensional array, storage is more complex. A 2D array can be viewed as an array of arrays. Memory allocation involves first allocating space for references to each row (stored contiguously), then allocating separate contiguous blocks for each row's elements.

Practical Exercises

1. Input and Store Five Numbers

import java.util.Scanner;

public class InputArray {
    public static void main(String[] args) {
        int[] values = new int[5];
        Scanner input = new Scanner(System.in);
        System.out.println("Enter five numbers:");
        for (int count = 0; count < 5; count++) {
            System.out.print("Number " + (count + 1) + ": ");
            values[count] = input.nextInt();
        }
        for (int count = 0; count < 5; count++) {
            System.out.println("Value " + (count + 1) + ": " + values[count]);
        }
    }
}

2. Generate and Display an Array

public class GenerateArray {
    public static void main(String[] args) {
        int[] sequence = new int[7];
        for (int position = 0; position < 7; position++) {
            sequence[position] = position * 2;
            System.out.println(sequence[position]);
        }
    }
}

3. Find Maximum Value in an Array

import java.util.Scanner;

public class FindMax {
    public static void main(String[] args) {
        int[] data = new int[5];
        Scanner input = new Scanner(System.in);
        System.out.println("Enter five numbers:");
        for (int idx = 0; idx < 5; idx++) {
            System.out.print("Number " + (idx + 1) + ": ");
            data[idx] = input.nextInt();
        }
        int maximum = data[0];
        for (int idx = 1; idx < 5; idx++) {
            if (data[idx] > maximum) {
                maximum = data[idx];
            }
            System.out.println("After comparison " + idx + ", max is " + maximum);
        }
    }
}

4. Find Minimum Value in an Array

import java.util.Scanner;

public class FindMin {
    public static void main(String[] args) {
        int[] dataset = new int[5];
        Scanner input = new Scanner(System.in);
        System.out.println("Enter five numbers:");
        for (int pos = 0; pos < 5; pos++) {
            System.out.print("Number " + (pos + 1) + ": ");
            dataset[pos] = input.nextInt();
        }
        int minimum = dataset[0];
        for (int pos = 1; pos < 5; pos++) {
            if (dataset[pos] < minimum) {
                minimum = dataset[pos];
            }
            System.out.println("After comparison " + pos + ", min is " + minimum);
        }
    }
}

5. Bubble Sort Implemantation

import java.util.Scanner;

public class BubbleSort {
    public static void main(String[] args) {
        int[] elements = new int[5];
        Scanner input = new Scanner(System.in);
        System.out.println("Enter five numbers:");
        for (int i = 0; i < 5; i++) {
            System.out.print("Number " + (i + 1) + ": ");
            elements[i] = input.nextInt();
        }
        int size = elements.length;
        for (int outer = 0; outer < size; outer++) {
            for (int inner = 0; inner < size - outer - 1; inner++) {
                if (elements[inner] > elements[inner + 1]) {
                    int temp = elements[inner];
                    elements[inner] = elements[inner + 1];
                    elements[inner + 1] = temp;
                }
            }
        }
        System.out.println("Sorted array:");
        for (int i = 0; i < 5; i++) {
            System.out.println(elements[i]);
        }
    }
}
Tags: Java

Related Articles

Understanding Strong and Weak References in Java

Strong References Strong reference are the most prevalent type of object referencing in Java. When an object has a strong reference pointing to it, the garbage collector will not reclaim its memory. F...

Comprehensive Guide to SSTI Explained with Payload Bypass Techniques

Introduction Server-Side Template Injection (SSTI) is a vulnerability in web applications where user input is improper handled within the template engine and executed on the server. This exploit can r...

Implement Image Upload Functionality for Django Integrated TinyMCE Editor

Django’s Admin panel is highly user-friendly, and pairing it with TinyMCE, an effective rich text editor, simplifies content management significantly. Combining the two is particular useful for bloggi...

Leave a Comment

Anonymous

◎Feel free to join the discussion and share your thoughts.