Java Program to Find the Length of an Array

In the previous article, we have seen Java Program to Sort the Elements of an Array in Descending Order

In this article we are going to see how we can find length of an array in Java.

Java Program to Find the Length of an Array

Array is a data structure which stores a fixed size sequential collection of values of single type. Where with every array elements/values memory location is associated. Each array elements have it’s own index where array index starts from 0.

In Array set of variables referenced by a single variable name and it’s array index position. It is also called as a container object which contains elements of similar type.

Declaration of an array:

dataType[] arrayName; (or)                              //Declaring an array
dataType []arrayName; (or)
dataType arr[];

Instantiation of an Array:

arrayName = new datatype[size];                    //Allocating memory to array

Combining both Statements in One:

dataType[] arrayName = new dataType[size] //Declaring and Instantiating array

Initialization of an Array:

arrayName[index-0]= arrayElement1             //Initializing the array

...

arrayName[index-s]= arrayElementS

Combining all Statements in One:

dataType arrayName[ ]={e1,e2,e3};               //declaration, instantiation and initialization

Method-1: Java Program to Find the Length of an Array By Using length function

Approach:

  • Take an array with elements in it.
  • Print out the array elements.
  • Pass the array to the length function and print the length of the array.

Program:

import java.util.Arrays;

public class array
{
    public static void main(String args[])
    {
        // Creating the array
        int arr[] = {12,2,34,54,6};

        // Prints the array elements
        System.out.println("The array elements are"+Arrays.toString(arr));
        // The length of the array using .length
        System.out.println("The length of the array is "+arr.length);
    }
}

Output:

The array elements are[12, 2, 34, 54, 6]
The length of the array is 5

Have you mastered basic programming topics of java and looking forward to mastering advanced topics in a java programming language? Go with these ultimate Advanced java programs examples with output & achieve your goal in improving java coding skills.

Related Java Programs: