How to find the size of an array in Java
Hi coders! In this tutorial, we are going to learn about the array data structure. The task is to find the size of an array in Java.
Now as the array is a collection of variables of the same data type. The memory allocation of an array is contiguous.
To create an array in java is like creating an object in Java, suppose we are creating an int array of size 5 we will write like
int[] arr = new int[5] so “arr” will store the reference of array object of integer type which is of size 5. As we create an array, a variable named as length is also declared with that array. this variable tells the size of array.
To know the size of array we write “arr.length”.
Suppose an int array is :
int[] arr = {1, 2, 3, 4, 5, 6}, here if we write arr.length then the output would be “6”.
Code to find the size of an array in Java
public class ArraySize{ //driver function public static void main(String[] args){ // array declaration and initialisation int [] arr = {3, 5, 7, 1, 2, 9, 10, 12}; int size; // size will store the size of array size = arr.length; System.out.println("The size of the array is: "+size); } } // Code is provided by Anubhav Srivastava
Output: The size of the array is 8
Now if the array is of character then also the “.length ” can be used to find the size of array.
If the array isĀ char[] charArr = {‘a’, ‘b’, ‘g’, ‘t’, ‘i’}, if we write charArr.length then the output will be the size of the array
Java program to find the size of an array of character
public class ArraySize { //driver function public static void main(String[] args) { //character array char[] charArr = {'a', 'b', 'c','g'}; int size ; size = charArr.length; System.out.println("Size of the array is: "+size); } } //code is provided by Anubhav Srivastava
Output: Size of the array is: 4
Hope you like the solution.
Leave a Reply