Java – Two dimensional array length

Previous
Next

Length of array:

  • When we call length variable on array object, it returns number of rows as length.
  • We need to call length variable on each row to find the size of row(number of columns)
class Main
{
	public static void main(String[] args) 
	{
		int arr[][] = new int[3][2];
		System.out.println(arr.length);
		System.out.println(arr[0].length);
		System.out.println(arr[1].length);
		System.out.println(arr[2].length);
	}
}

We can iterate the array using length variable as follows:

class Main
{
	public static void main(String[] args) 
	{
		float arr[][] = new float[4][3];
		System.out.println("Array elements are : " );
		for (int i=0 ; i<arr.length ; i++)
		{
			for (int j=0 ; j<arr[i].length ; j++)
			{
				System.out.print(arr[i][j]+"  ");
			}
			System.out.println();
		}
	}
}

We can initialize an array directly using assignment operator as follows:

class Main
{
	public static void main(String[] args) 
	{
		int arr[][] = {{1,2,3}, {4,5,6},{7,8,9}};
		System.out.println("Array elements are : " );
		for (int i=0 ; i<arr.length ; i++)
		{
			for (int j=0 ; j<arr[i].length ; j++)
			{
				System.out.print(arr[i][j]+"  ");
			}
			System.out.println();
		}
	}
}
Previous
Next

Add Comment

Courses Enquiry Form