Array Basics

 

Array Basics

 

An array is a container object that holds a fixed number of values of a single type. We do not need to create different variables to store many values, instead we store them in different indices of the same objects and refer them by these indices whenever we need to call them.


Syntax:

Datatype[] arrayName = {val1, val2, val3,……. valN}

Note: array indexing in java starts from [0].

 

There are two types of array in java:


  • Single Dimensional Array
  • Multi-Dimensionalal Array


We will see how to perform different operations on both the type of arrays,

A. Length of an array:

Finding out the length of an array is very crucial when performing major operations. This is done using the .length property:


Example:


public class ArrayExample {
    public static void main(String[] args) {
        //creating array objects
        String[] cities = {"Delhi", "Mumbai", "Lucknow", "Pune", "Chennai"};
        int[] numbers = {25,93,48,95,74,63,87,11,36};

        System.out.println("Number of Cities: " + cities.length);
        System.out.println("Length of Num List: " + numbers.length);
    }
}


Output:

Number of Cities: 5
Length of Num List: 9

 

B. Accessing array elements:

Array elements can be accessed using indexing. In java, indexing starts from 0 rather than 1.


Example:


public class ArrayExample {
    public static void main(String[] args) {
        //creating array objects
        String[] cities = {"Delhi", "Mumbai", "Lucknow", "Pune", "Chennai"};
        int[] numbers = {25,93,48,95,74,63,87,11,36};

        //accessing array elements using indexing
        System.out.println(cities[3]);
        System.out.println(numbers[2]);
    }
}


Output:

Pune
48

 

C. Change array elements:

The value of any element within the array can be changed by referring to its index number.


Example:


public class ArrayExample {
    public static void main(String[] args) {
        //creating array objects
        String[] cities = {"Delhi", "Mumbai", "Lucknow", "Pune", "Agra"};

        cities[2] = "Kasganj";
        System.out.println(cities[2]);
    }
}


Output:

Kasganj