Example of single dimensional java array

7/27/2021

Here we learn how to implement Example of single dimensional java array.

Go Back

Java Array: Example of a Single-Dimensional Array

Arrays are an essential data structure in Java that allow storing multiple values of the same type in a contiguous memory location. In Java, an array is an object that holds elements of a similar data type and is accessed using an index.

Understanding Java Arrays

  • Arrays store similar elements in a fixed size.
  • They are index-based, meaning each element can be accessed using its position.
  • Java arrays are objects, and their size must be defined at the time of declaration.
Here we learn how to implement Example of single dimensional java array.

Example: Single-Dimensional Java Array

The following example demonstrates how to declare, instantiate, initialize, and traverse a single-dimensional array in Java.

class B {
    public static void main(String args[]) {
        int a[] = new int[5]; // Declaration and instantiation
        
        a[0] = 10; // Initialization
        a[1] = 20;
        a[2] = 70;
        a[3] = 40;
        a[4] = 50;

        // Traversing and printing array elements
        for (int i = 0; i < a.length; i++)
            System.out.println(a[i]);  
    }
}

Explanation of the Code

  1. Declaration & Instantiation:
    • int a[] = new int[5]; → Declares an integer array with a fixed size of 5.
  2. Initialization:
    • Each index in the array is assigned a value.
  3. Traversal:
    • The for loop iterates through the array and prints each element.

Output of the Program

10
20
70
40
50

Conclusion

Using a single-dimensional array in Java helps efficiently store and manipulate data. Arrays are a fundamental part of Java programming and are widely used in various applications.

For more Java tutorials, stay connected with us on Instagram and Facebook!

Table of content