Declare an array in java without size

Tags: ,



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

for(int i=0; i<=myarray1.length - 1; i++){
    for (int j=0; j<=myarray2.length - 1; j++){
        if (myarray1[i] == myarray2[j]){
            myarray5[k] = myarray2[j];
            k++;
        }       
    }       
}

and also when am printing the array:

for (int i=0; i<=myarray3.length-1; i++){
    System.out.print(myarray3[i]+",");
}

Answer

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

You can dynamically declare an array as shown below.

  int size = 5; // or anyother value you want
  int[] array = new int[size];

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

  List<Integer> list = new ArrayList<>();
  list.add(5); //adds number 5 to the list
  int number = list.get(0); // Returns Element which is located at position 0 (so in this example in number will be "5");


Source: stackoverflow