Object Oriented Programming with Java

⌘K
  1. Home
  2. Docs
  3. Object Oriented Programmi...
  4. Fundamental Programming S...
  5. Array in Java

Array in Java

An array in Java is a data structure that stores multiple values of the same type in a single variable in contiguous memory locations.

Thank you for reading this post, don't forget to subscribe!
  • They are useful for storing and managing collections of data.

Key Points to Remember:

  • Arrays have fixed size once created.
  • Elements are stored in contiguous memory locations.
  • First element is accessed by index 0
  • All elements must be of the same data type
  • Array access is O(1) time complexity.
  • Arrays are objects in Java, stored in heap memory.

A one-dimensional array is a linear collection of elements of the same data type stored in a single row.

Syntax:

dataType[] arrayName = {value1, value2, value3, ...};

Declaration and Initialization:

public class OneDArrayExample {
    public static void main(String[] args) {
    
         // Declaration
        int[] numbers;
        
        // Declaration with initialization
        int[] numbers = {10, 20, 30, 40, 50};

        System.out.println("Using for loop:");
        for (int i = 0; i < numbers.length; i++) {
            System.out.println("Element at index " + i + ": " + numbers[i]);
        }
    }
}

Accessing Elements:

public class OneDArrayExample {
    public static void main(String[] args) {

int[] arr = {10, 20, 30, 40, 50};
System.out.println(arr[0]);  // Output: 10 (first element)
System.out.println(arr[4]);  // Output: 50 (last element)
arr[2] = 100;  // Modify element at index 2

    }
}

Java supports arrays of arrays, commonly used to represent matrices or tables.

Two-Dimensional Arrays:

syntax:

dataType[][] arrayName = {
    {value1, value2},
    {value3, value4}
};

Example:

public class TwoDArrayExample {
    public static void main(String[] args) {
        int[][] matrix = {
            {1, 2, 3},
            {4, 5, 6},
            {7, 8, 9}
        };

        System.out.println("2D Array Output:");
        for (int i = 0; i < matrix.length; i++) {
            for (int j = 0; j < matrix[i].length; j++) {
                System.out.print(matrix[i][j] + " ");
            }
            System.out.println(); // new line
        }
    }
}

How can we help?