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?
Java String length() Method The length() method returns the length of a specified string. Note: The length of an empty string is 0.
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.
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.
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.
It contains the allocated size, 10
. The unassigned indexes will contain the default value which is 0
for int
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With