java

Java Arrays


What is Arrays?

Array is a variable that allows you to store multiple values of the same data type under a single variable name.

Note :- 
1. Arrays are used to group elements of the same type and provide a way to access them using an index.

2. The index starts from 0 for the first element and increments by 1 for each subsequent element.

 

Syntax (array literal)

// Declare and initialize an array of integers without 'new'

data_type[] var_name = {value1, value2, value3, value4, value5};

 

Example

public class ArraysExample {
    public static void main(String[] args) {
        // Declare and initialize an array of integers
        int[] numbers = {1, 2, 3, 4, 5};
        // Priting arrays value using for each loop

        for (int num : numbers) {
            System.out.println("Element: " + num);
        }
    }
}

 

Syntax (new keyword)

// Declare and initialize an array of integers using 'new'
data_type[] var_name = new type[size];

 

Example

public class ArrayExample {
    public static void main(String[] args) {
        // Declare and initialize an array of integers using 'new' keyword
        int[] numbers = new int[5];

        // Assign values to array elements
        numbers[0] = 10;
        numbers[1] = 20;
        numbers[2] = 30;
        numbers[3] = 40;
        numbers[4] = 50;

        // Display elements of the array using for loop

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

 

Java Arrays Type

1. Single-Dimensional Arrays (1D)

Syntax

String[] singleDimensionalArray = {"Ankush","Akhilesh","Rohit","Altaf"};

Note:- The array example given above is called 1D  array.

 

2. Multi-Dimensional Arrays (2D)

Syntax

int[][] twoDimensionalArray = {
    {1, 2, 3},
    {4, 5, 6},
    {7, 8, 9}
};


Example

public class TwoDimensionalArrayExample {
    public static void main(String[] args) {
        // Declare and initialize a two-dimensional array
        int[][] twoDArray = {
            {1, 2, 3},
            {4, 5, 6},
            {7, 8, 9}
        };

        // Display elements of the two-dimensional array
        for (int i = 0; i < twoDArray.length; i++) {
            for (int j = 0; j < twoDArray[i].length; j++) {
                System.out.print(twoDArray[i][j] + " ");
            }
            System.out.println(); // Move to the next line after each row
        }
    }
}