Skip to content
Advertisement

Declare an array in java without size

Hello am trying to declare an array in java but i do not want the array to have a specific size because each time the size must be different.

I used this declaration: int[] myarray5;

but when am trying the below code there is an error on myarray5

JavaScript

and also when am printing the array:

JavaScript

Advertisement

Answer

There is a NullPointerException because you declared but never initialized the array.

You can dynamically declare an array as shown below.

JavaScript

Or you use a list. Which allows to dynamically change the size. E.g:

JavaScript
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement