How to create Array program in java

class Array_TechSarvam 
{
    public static void main(String args[]) 
    {
        // Declaration and instantiation
        int a[] = new int[5];

        // Initialization
        a[0] = 10;
        a[1] = 20;
        a[2] = 70;
        a[3] = 40;
        a[4] = 50;

        // Printing array elements
        for (int i = 0; i < a.length; i++) // length is the property of array
        {
            System.out.println(a[i]);
        }
    }
}

Step-by-Step Explanation of the Program:

Let’s get more up close and personal with this line by line code.

1. Declaration and Instantiation of Array

Int a[] = new int[5];

The declaration is making an array named a of type int that stores 5 integers.

new int[5] instantiates a new array of five elements, and all the elements are initially assigned 0: that is, the default initial value for int arrays in Java.

In this step, the array a becomes:

[0, 0, 0, 0, 0]

2. Array Initialization:

a[0] = 10;

a[1] = 20;

a[2] = 70;

a[3] = 40;

a[4] = 50;

Each of the elements of the array is assigned a value. Precisely

a[0] is taken 10.

a[1] is taken 20.

a[2] is taken 70.

a[3] is taken 40.

a[4] = 50;

As soon as it is done the array a has the form of:

[10, 20, 70, 40, 50]

3. Displaying Elements in an Array

for (int i = 0; i < a.length; i++) {

System.out.println(a[i]);

  }

  • The for loop in order to process the elements from the array.
  • a.length is the field that prints the length of the array (in this case, 5).
  • The for loop will run from i = 0 to i = 4inclusive; that is, it will iterate over all 5 elements of the array.
  • System.out.println(a[i]); prints every single element of the array to the console, one at a time.

Output:

10

20

70

40

50

Key Concepts:

1. Array Declaration and Instantiation:

int a[] = new int[5]; declares an array a of type int and size 5. This provides memory for five integer elements.

2. Array Indexing:

Java arrays are 0-indexed. This implies that the first element is located at a[0], the second at a[1], and continues to a[4].

3. Array Length:

a.length returns the number of elements in the array (in this case, 5). It is an array property in Java.

4. For Loop for Iteration:

The for loop iterates over the array by using the index of the array. It begins at index 0 and goes up to a.length – 1, which is the last valid index of the array.

5. Array Initialization:

Array elements are initialized individually by specifying the index (a[0], a[1], etc.) and assigning a value.

Conclusion:

This program demonstrates the declaration, initialization, and traversal of an array in Java. It uses a simple for loop to iterate over the elements of the array and print them to the console.

Leave a Comment

Your email address will not be published. Required fields are marked *