Unit 5 Java : Array

0

Array

Array is an object which contains elements of a similar data type. Additionally, The elements of an array are stored in a contiguous memory location. It is a data structure where we store similar elements. We can store only a fixed set of elements in a Java array.

Array in Java is index-based, the first element of the array is stored at the 0th index, 2nd element is stored on 1st index and so on. Index of an array always starts from 0.

Advantages

  • Code Optimization: It makes the code optimized, we can retrieve or sort the data efficiently.

  • Random access: We can get any data located at an index position.

Disadvantage

  • Size Limit: We can store only the fixed size of elements in the array. It doesn’t grow its size at runtime. To solve this problem, collection framework is used in Java which grows automatically.

Types of array.

  • Single Dimensional Array

  • Multidimensional Array

Single-Dimensional Array in Java:

A single-dimensional array is a type of array that holds a collection of elements of the same type. It is essentially a list of values stored in a single line.

Syntax to Declare an Array in Java:

dataType[] array_name;
dataType []array_name;
dataType array_name[];

Multi-Dimensional Array in Java:

A multi-dimensional array in Java is an array of arrays. It’s an array whose elements are also arrays.

Syntax to Declare a Multi-Dimensional Array in Java:

dataType[][] array_name; // for two-dimensional array 
dataType[][][] array_name; // for three-dimensional array

Example:

int[] singleArray = new int[5]; // Initializes an array of 5 integers

int[][] twoDArray = new int[3][4]; // Initializes a 3x4 matrix (3 rows and 4 columns)

Example:

Here, we will be using loops and array to input n number of elements in an array and print them.

import java.util.Scanner;

public class Kalokalam{
    public static void main(String[] args) {
        int n;
        Scanner sc = new Scanner(System.in);

        System.out.print("Enter the number of elements you want to store: ");
        // Reading the number of elements from the user input
        n = sc.nextInt();

        // Creates an array in the memory of the length provided by the user
        int[] array = new int[n];

        System.out.println("Enter the elements of the array: ");
        for (int i = 0; i < n; i++) {
            // Reading array elements from the user
            array[i] = sc.nextInt();
        }

        System.out.println("Array elements are: ");
        // Accessing array elements using a for loop
        for (int i = 0; i < n; i++) {
            System.out.println(array[i]);
        }
    }
}

Output:

Enter the number of elements you want to store: 
>> 3
Enter the elements of the array: 
>> 1
>> 2
>> 3
Array elements are: 
1
2
3

Leave a Reply

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