×

How to find the length of an Array in Java

Arrays:

An array is a sort of container object that stores constant quantities of values of a single type in one memory area. A finite number of items must all be of the same data type in order to store them in this data structure. Index-based access is offered by arrays, meaning that the first element of the array is stored at index 0, the second element is stored at index 1, and so on. It should be noted that arrays are also objects in Java, inheriting the Object class and implementing the interfaces. Any form of primitive value or object can be stored in an array. Java allows arrays in either a single dimension or several dimensions.

Array Declaration in Java:

datatype array[] = new datatype[size];

Example:

import java.io.*;
import java.util.*;
class Demo
{
     public static void main(String args[])
     {  
        Scanner sc = new Scanner(System.in);  
          int a[] = new int[5];
          for(int i=0; i<5; i++)  
        {  
              a[i]=sc.nextInt();  }  
           for (int i=0; i<5; i++)   
          {  
                 System.out.println(a[i]);  
           }  
      }
}

Output:

1 2 3 5 6
1
2
3
5
6

Length of an Array in Java:

In Java, an array is a data structure that holds numerous components of the same data type. Array length has a variety of uses in programming. The length of an array is important information to have while managing and performing various actions on it.

When we initialise an array, its length property is automatically assigned, and we may access it using Variable.length method.

datatype array[] = new datatype[size];
int a = array.length;

Example:

import java.io.*;
import java.util.*;
class Demo
{
     public static void main(String args[])
     {  
        Scanner sc = new Scanner(System.in);  
          int a[] = new int[5];
           int b = a.length;
           System.out.println(“Array size = “ + b);
          for(int i=0; i<a.length; i++)  
        {  
              a[i]=sc.nextInt();  }  
           for (int i=0; i<a.length; i++)   
          {  
                 System.out.println(a[i]);  
           }  
      }
}

Output:

9 6 3 8 5
Array size = 5
9
6
3
8
5

Length of Multidimensional Array in Java:

If we have a two-dimensional array named array, we can use array.length and array[index].length to determine the parent and child lengths.

Example:

import java.io.*;
import java.util.*;
class Length {
  public static void main(String args[]) {
    
    
    int array[][] = {{40,50,60},{70,80,90},{100,110,120}};
    System.out.print("array length = ");
    System.out.println(array.length);
    System.out.println("array[] length = " + array[0].length);
  }
}

Output:

array length = 3
array[] length = 3

Difference between Java Array Length vs length()

In Java, using rounded brackets at the end of a word denotes the calling of a method.

The length of an array in Java refers to the total number of elements it can contain. By using the dot operator and the array name, we can utilise this length attribute or variable to determine the size of an array in Java.

In Java, the final method length() is accessible to string object types. It can be used to determine how many characters are in a string.

Example:

import java.io.*;
import java.util.*;
 class Size{
    public static void main(String args[])
    {
        int[] a= new int[25];
        System.out.println("Array size = "+ a.length);
        String Str= "Javatpoint";
        System.out.println("String size = "+ Str.length());
    }
}

Output:

Array size = 25
String size = 10

Length of ArrayList in Java

The size() method of the Java class java.util.ArrayList can be used to determine the length or size of an ArrayList. The amount of entries in the array list is the size() method's return value, which is an integer. It is distinct from the array's length that serves as the ArrayList's backing array, which is referred to as the ArrayList's capacity. The default value of ArrayList is 10 when user did not specify the size of ArrayList. When the size (the number of elements in the array list) increases beyond a certain point, ArrayList automatically resizes because it is a growable array.

An ArrayList is also known as an empty ArrayList when it is first created, and size() will return zero in this case.

Example:

import java.io.*;
import java.util.*;


class Length{
  public static void main(String args[]) {


    ArrayList<String> names = new ArrayList<>();
    int size = names.size();
    System.out.println("Size of array list (before): " + size);


    names.add("David");
    names.add("Charle");
    names.add("Jack");
    size = names.size();


    System.out.println("Size of ArrayList (after): " + size);
    }
}

Output:

Size of array list (before): 0
Size of array list (after): 3

Related Topics

Packages in Java

Packages in Java can be defined as an assortment for grouping various classes and interfaces based on their performance. It is a catalog for holding various java files. They provide...

4 minutes read.

Buffer reader to read string in Java

The Buffered Reader class of Java is used to read the stream of characters from the input stream. Program to read string using Buffer reader import java.io.*; class  Demo {   public static void main(String...

3 minutes read.

Java Command Line Argument

Command-line arguments are passed to the main() method when we want to pass information into a program during runtime. It is the information that directly follows the program’s name on the...

1 minute read.

Java.net.ConnectionException

java.net.ConnectException: Connection rejected: the interface is the most continuous sort of happening, organizing special cases in Java at whatever point the product is in client-server engineering and attempting to make...

3 minutes read.

JRE (Java Runtime Environment)

JRE is an installation package that provides an environment to run the Java program on any Operating System. It does not deal with the development process of any application. It is a part...

2 minutes read.

Check the presence of Substring in a String in java

In java, the string can be treated as class and datatype. The string contains words and numbers but should be in double-quotes. Example: ” Omsairam” Substring The part of the string is called...

2 minutes read.

Java LinkedList

LinkedList Java The Java LinkedList is used to store the elements by using a doubly linked list. It contains the duplicate items, also maintains the order of the insertion, the class...

5 minutes read.

Series Program in Java

Series Program in Java The series program in Java is written to print the mathematical series such as the Fibonacci series, Pell series, etc. A few of the renowned series are...

12 minutes read.

Java Boolean logicalAnd() Method

The logicalAnd() method of Java Boolean class returns the result of implementing logicalAND operation on the specified Boolean operands. Syntax:public static boolean logicalAnd (boolean a, boolean b) Parameters:The parameters ‘a’ and ‘b’...

2 minutes read.

Java Integer numberOfLeadingZeros() method

The numberOfLeadingZeros()  method of Java Integer class returns the total number of zero bits preceding the highest-order one-bit in the 2’s complement binary representation of the specified int value.  Syntax public static...

1 minute read.

How to sort a String in Java

Sorting is the process of putting the elements in a certain order, either ascending or descending. Mostly the alphabetical order or natural order is used for a string. In other...

5 minutes read.

What is new in Java 17?

Java 17 LTS is the most recent long-term support release for the Java SE platform. Under the Oracle No-Fee Terms and Conditions License, which stands for long-term support, JDK 17...

6 minutes read.

Java Byte Code

Java byte code is really a powerful mechanism which makes Java a portable and platform-independent programming language. There are two software components which go along and make this byte code...

3 minutes read.

How to Convert String to char in Java

How to Convert String to char in Java There are two methods to convert String to char are: Using charAt() method Using tocharArray() method Using charAt() method This is the method of String class that...

3 minutes read.

How to Convert Date to String in Java

How to Convert Date to String in Java We need to convert Date to String in Java may for displaying purpose. We can convert Date to String in Java using the format() method of java.text.DateFormat class. There...

2 minutes read.

Unicode System in Java

In this tutorial, we will understand the meaning and emergence of the Unicode system in java. The Unicode system is one of the important and useful features in the world...

6 minutes read.

Getter and Setter Method in Java Example

In Java programming, getter and setter methods are often employed. The values of class fields can be accessed and changed using Java's getter and setter methods. A private access specifier...

6 minutes read.

Java Integer sum() method

The sum() method of Java Integer class add the two specified integers values. It returns the same result as given by + operator. Syntax public static int sum (int a, int b)  Parameters The...

1 minute read.

Composition in Java

Composition Java uses the composition method to implement a has-a connection. Composition allows us to reuse code in the same way that Java inheritance does. The "is-a" relationship is implemented using the...

3 minutes read.

Java For Loop

A for loop is used to execute a set of statements for a fixed number of times. It takes the following form: for (initialization; condition; update) { statements; } The for loop defines...

2 minutes read.