Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Array Length in Java

Tags:

java

arrays

I declared an array as shown below:

int[] arr = new int[10]; 

Then I assigned following values to the array:

arr[0] = 1; arr[1] = 2; arr[2] = 3; arr[3] = 4; 

Then I declared and initialized an integer variable:

int arrayLength = arr.length; 

This will be useful to find actual size but is there any method to find logical size of the array?

like image 972
Kiran Bhat Avatar asked Jan 06 '12 09:01

Kiran Bhat


People also ask

What is length () in Java?

Java String length() Method The length() method returns the length of a specified string. Note: The length of an empty string is 0.

How do you count the size of an array in Java?

With the help of the length variable, we can obtain the size of the array. Examples: int size = arr[]. length; // length can be used // for int[], double[], String[] // to know the length of the arrays.

How do you check the length of an array?

The simplest procedural way to get the value of the length of an array is by using the sizeof operator. First you need to determine the size of the array. Then you need to divide it by the size of one element. It works because every item in the array has the same type, and as such the same size.

What does length 1 mean in array in Java?

length-1]. An attempt to refer to an array element with an index outside the range from zero to A. length-1 causes an ArrayIndexOutOfBoundsException. Arrays in Java are objects, so an array variable can only refer to an array; it does not contain the array. The value of an array variable can also be null.


1 Answers

It contains the allocated size, 10. The unassigned indexes will contain the default value which is 0 for int.

like image 178
Kai Avatar answered Oct 17 '22 03:10

Kai