Arrays in Java

Mannan Ul Haq
0

Arrays in Java are used to store multiple elements of the same data type in a contiguous memory block. They provide a convenient way to work with collections of values and are widely used in programming. Arrays can be one-dimensional or multi-dimensional.


1. One-Dimensional Arrays:

A one-dimensional array, also known as a linear array, is a collection of elements of the same data type arranged in a single row.

Array Length = 4
First Index = 0
Last Index = 3

In Java, each element in an array is associated with a number known as an array Index. We can access elements by using those indices.


Declaration and Initialization:

To declare a one-dimensional array in Java, you need to specify the data type of the elements and the size of the array. The size represents the number of elements the array can hold. The syntax for declaring a one-dimensional array is as follows: 


dataType[] arrayName = new dataType[arraySize];

 

Here, dataType refers to the type of data the array will store, such as int, char, float, etc. arrayName is the name given to the array, and arraySize denotes the number of elements the array can hold. 


There are multiple ways to create and initialize a one-dimensional array in Java. Here are four different approaches:


1. Creating an array of four elements and adding values right away:


int[] numbers = new int[] { 10, 20, 30, 40 };


In this approach, we declare and initialize the `numbers` array with four elements and their corresponding values in a single line. The Java compiler automatically determines the size based on the number of elements provided in the array initializer.


2. Creating an array of four elements, omitting the `new` keyword:


int[] numbers = { 10, 20, 30, 40 };


In this approach, we can further simplify the declaration by omitting the `new` keyword. The compiler automatically infers the size based on the number of elements in the array initializer. This is known as "array initializer shorthand."


3. Creating an array of four elements and adding values later using loop:


int[] numbers = new int[4];

// Use a for loop to initialize the array elements
for (int i = 0; i < 4; i++)
{
    // Assign values to each element based on the loop counter (i)
    numbers[i] = i + 1;
}


In this approach, we declare an array called `numbers` that can hold four elements of type `int`. The array is created with a size of four, but it does not contain any values initially. We can later assign values to each element individually.


It is important to understand that when you declare an array and plan to initialize it later, you must use the `new` keyword to allocate memory for the array:


// Declaration of an integer array
int[] numbers;

// Initialization using the 'new' keyword
numbers = new int[] { 1, 2, 3, 4, 5 };

// Attempting to initialize without 'new' will result in an error
numbers = { 1, 2, 3, 4, 5};

 

Accessing Elements:

Elements in a one-dimensional array can be accessed using the index.

Example:

 

int num = numbers[2]; // Accessing the element at index 2


Printing Array Elements:

We can print array using loop:

for (int index = 0; index < SIZE; index++)
    System.out.print(array[index] + " ");


For example:


// import the Scanner class
import java.util.Scanner;

class Program
{
    public static void main(String[] args)
    {
        int arraySize = 5;  // Size of the array
        int[] numbers = new int[arraySize];  // Declare the array to store user input

        // Prompt the user to enter values for the array
        System.out.println("Enter " + arraySize + " numbers:");

        // Read user input and store it in the array
        Scanner input = new Scanner(System.in);
        for (int i = 0; i < arraySize; i++)
        {
            System.out.print("Number " + (i + 1) + ": ");
            numbers[i] = input.nextInt();
        }
        input.close();

        // Print the array elements
        System.out.print("The array elements are: ");
        for (int i = 0; i < arraySize; i++)
        {
            System.out.print(numbers[i] + " ");
        }
        System.out.println();
    }
}


Finding LENGTH of Array:

To find the number of elements in a one-dimensional array, you can use the 'length' property.

int[] numbers = { 10, 20, 30, 40 };
int length = numbers.length; // length will be 4

 


2. Two-Dimensional Arrays:

A two-dimensional array, also known as a matrix, is a collection of elements arranged in rows and columns. It can be visualized as a table or a grid.

Declaration and Initialization:

To declare a two-dimensional array in Java, you need to specify the data type of the elements, the number of rows, and the number of columns. The syntax for declaring a two-dimensional array is as follows:

dataType[][] arrayName = new dataType[rowSize][columnSize];

Here, `dataType` represents the type of data the array will store, such as `int`, `char`, `float`, etc. `arrayName` is the name given to the array, `rowSize` denotes the number of rows, and `columnSize` represents the number of columns.


Similarly, there are multiple ways to create and initialize a two-dimensional array in Java. Here are four different approaches:

1. Creating a 2D array of four rows and three columns and adding values right away:


int[][] matrix = new int[][] {
    { 1, 2, 3 },
    { 4, 5, 6 },
    { 7, 8, 9 },
    { 10, 11, 12 }
};

In this approach, we declare and initialize the `matrix` array with four rows and three columns, along with their corresponding values in a single line. Java compiler automatically determines the size of each dimension based on the number of elements provided in the array initializer.

2. Creating a 2D array and omitting the `new` keyword:


int[][] matrix = {
    { 1, 2, 3 },
    { 4, 5, 6 },
    { 7, 8, 9 },
    { 10, 11, 12 }
};

In this approach, we can further simplify the declaration by omitting the `new` keyword. The compiler automatically infers the size of each dimension based on the number of elements in the array initializer. This is known as "array initializer shorthand" for 2D arrays.

4. Creating a 2D array and adding values later using nested loops:


int[][] matrix = new int[4][3];

// Use nested loops to initialize the array elements
for (int row = 0; row < 4; row++)
{
    for (int col = 0; col < 3; col++)
    {
        // Assign values to each element based on row and column indices
        matrix[row][col] = (row + 1) * (col + 1);
    }
}

 

Accessing Elements:

In a two-dimensional array, elements are accessed using both the row and column indices. The row index specifies the row's position, and the column index specifies the column's position. The indices start from 0.

To access an element, you can use the array name followed by the row and column indices in square brackets:

arrayName[rowIndex][columnIndex];

For example, to access the element in the second row and third column of a 2D array named `matrix`, you would use `matrix[1][2]` because the indices start from 0.


Printing Array Elements:

To print the elements of a two-dimensional array, you can use nested loops. The outer loop iterates over the rows, and the inner loop iterates over the columns.

for (int i = 0; i < rowSize; i++)
{
    for (int j = 0; j < columnSize; j++)
    {
        System.out.print(arrayName[i][j] + " ");
    }
    System.out.println(); // Move to the next line after printing each row
}

For example:

// import the Scanner class
import java.util.Scanner;

class Program
{
    public static void main(String[] args)
    {
        int rows = 3;    // Number of rows in the array
        int columns = 3; // Number of columns in the array

        int[][] matrix = new int[rows][columns];  // Declare the 2D array to store user input

        // Prompt the user to enter values for the array
        System.out.println("Enter " + rows * columns + " numbers for the 2D array:");

        // Read user input and store it in the 2D array
        Scanner input = new Scanner(System.in);
        for (int i = 0; i < rows; i++)
        {
            for (int j = 0; j < columns; j++)
            {

                System.out.print("Element (" + i + ", " + j + "): ");
                matrix[i][j] = input.nextInt();
            }
        }
        input.close();

        // Print the 2D array elements
        System.out.println("The 2D array elements are:");
        for (int i = 0; i < rows; i++)
        {
            for (int j = 0; j < columns; j++)
            {
                System.out.print(matrix[i][j] + " ");
            }
            System.out.println();
        }
    }
}

Finding LENGTH of 2D-Array:

In Java, you can determine the length of any specific dimension of a multi-dimensional array using the .length attribute. It provides a straightforward way to get the number of elements in a particular row or column of a 2D array. This is particularly useful when dealing with arrays of varying sizes.


Let's see an example of how to use the .length function with a 2D array:

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

        int numRows = matrix.length; // Get the number of rows
        int numCols = matrix[0].length; // Get the number of columns

        System.out.println("Number of rows: " + numRows);
        System.out.println("Number of columns: " + numCols);
    }
}


3. Jagged Arrays:

Jagged arrays in Java are arrays of arrays, where each element of the main array can be an array itself. Unlike multi-dimensional arrays, jagged arrays allow each row to have a different number of elements, providing more flexibility in organizing and storing data.


The syntax for declaring a jagged array is as follows:


dataType[][] arrayName = new dataType[numRows][];


Here, `dataType` represents the type of data the array will store, such as `int`, `string`, etc. `arrayName` is the name given to the jagged array, and `numRows` denotes the number of rows in the main array.


After declaring the jagged array, you need to initialize each row individually with its own size using the `new` keyword:


arrayName[0] = new dataType[numColumnsForRow0];
arrayName[1] = new dataType[numColumnsForRow1];
// and so on...


You can also initialize the jagged array directly during declaration:


arrayName[0] = new dataType[] { value1, value2, ... }; // Row 0
arrayName[1] = new dataType[] { value3, value4, ... }; // Row 1
// and so on...


Here's an example of a jagged array of integers:


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


Accessing elements in a jagged array is similar to accessing elements in a regular multi-dimensional array. You use the row index followed by the column index (if applicable) to access specific elements:


int value = jaggedArray[rowIndex][columnIndex];


Iterating through a jagged array requires nested loops. You use an outer loop to iterate through each row and an inner loop to iterate through each element in that row:


for (int i = 0; i < jaggedArray.length; i++)
{
    for (int j = 0; j < jaggedArray[i].length; j++)
    {
        System.out.print(jaggedArray[i][j] + " ");
    }
    System.out.println(); // Move to the next line after printing each row
}



Arrays in Java provide a powerful tool for storing and manipulating collections of elements. They are versatile and widely used in various programming tasks.


Post a Comment

0Comments

Post a Comment (0)

#buttons=(Accept !) #days=(20)

Our website uses cookies to enhance your experience. Check Now
Accept !