Javatpoint Logo
Javatpoint Logo

Difference Between arr.length, arr[0].length and arr[1].length in Java

Java provides an attribute length that determines the length of an array. Every array has an in-built length property whose value is the size of the array. Size implies the total number of elements that an array can contain. The length property can be invoked by using the dot (.) operator followed by the array name. In this section, we will discuss what is the difference between array.length, array[0].length, and array[1].length.

array.length, array[0].length, and array[1].length usually used in the block array (more than one dimensional array). Each dimension has a length. For example, consider the following array.

arr.length, arr[0].length and arr[1].length in Java

The above array represents the tabular format of a block array that consists of 50 rows and 70 columns. Suppose, we are required to get the value of the index array[1][4], the value at the index is 30.

array[0] refers to the 0th row of the block array. While array[0].length refers to the columns associated with 0th row i.e. 70. Therefore, the answer would be 70.

array.length: The length property is used to find the array length.

array[0].length: The number of columns on row 0.

array[1].length: The number of columns on row 1.

In Java, Arrays are objects but not really looks like object. Because, Java allows us to use the index operator (i.e., using brackets[ ]).

As Arrays are objects, there are methods and instance variables. In particular, Arrays have a public instance variable called length. It determines the length of the array.

Normally, we should avoid using public instance variables to improve encapsulation. However, Java arrays use them, so we must use them as well.

Here's how to print a Java array using the length instance variable.

Consider the following code snippet.

In the above-defined array, the length is 5.

Let's understand the concept of array.length, array[0].length, and array[1].length through a Java program.

MatrixDemo.java

Output:

3
4
4

In the above program, we observe that mat.length is the total number of rows. mat[0].length is the number of columns in 0th row. mat[1].length should have the same value as mat[0].length. Therefore, it has the same number of columns as the first row.


Next TopicFuture in Java 8





Youtube For Videos Join Our Youtube Channel: Join Now

Feedback


Help Others, Please Share

facebook twitter pinterest

Learn Latest Tutorials


Preparation


Trending Technologies


B.Tech / MCA