Vikrant Kashyap Vikrant Kashyap - 7 months ago 8
Java Question

Difference between two dimensional different flavours type array ? Advantages of these of two type

I am trying to study

array
in depth. I tried so many multidimensional array but didn't understand

class Test
{
public static void main (String[] args) throws java.lang.Exception
{

String [][] obj1 = new String [10][5];
String [][] obj2 = new String [10][];

System.out.println(obj1[1].length);
System.out.println(obj2[1].length);
}
}


In this example , I have tried two double dimensional array.

String [][] obj1 = new String [10][5];
and
String [][] obj2 = new String [10][];
.

Now

System.out.println(obj1[1].length);
gives the length
5
as a Output. Totally Cleared.

In Second sysout statement throws
NullPointerException


System.out.println(obj2[1].length);
Totally UnCleared. because i am not trying to access the member variables only want to get the length.

So, why
NullPointerException
Here ? Is there really any advantage of Second type of array declaration ??

Please explain in details, found several Sources but still Confused.

Thanks

Answer

In String [][] obj2 = new String [10][]; you are initializing obj2 to refer to an array of 10 String[] elements. The elements of the array are initialized to null, which is why obj2[1].length throws a NullPointerException.

This type of declaration allows you to assign arrays of different lengths in the 2D array.

For example :

obj2[0] = new String[5];
obj2[1] = new String[10];

while in

String [][] obj1 = new String [10][5];

all the inner arrays have the same length of 5, since here you are initializing obj1 to refer to an array of 10 String[] elements, each of which is initialized to refer to an array of 5 String elements.