-3
int[] array = new int[scan.nextInt()];

I found this code online and don't understand it. I think it dynamically creates an array. Can someone explain what's going on?

shmosel
  • 42,915
  • 5
  • 56
  • 120
rahmor
  • 1
  • 2
  • It creates an array with the size specified by the next console input. – shmosel Feb 16 '17 at 22:59
  • 2
    Java does not have dynamic arrays, where "dynamic" means the size is variable at runtime. This is a statically sized array whose size is specified by user input. After it's created its size is constant and cannot be changed. – Jim Garrison Feb 16 '17 at 23:00
  • @Jim Garrison The array size will be defined at runtime (the user input must be at runtime). Java doesn't have a dynamic arrays, but thats what happenning behind the scenes. – אביב פישר Feb 16 '17 at 23:09
  • No, the array is being allocated at runtime with a size that is read in. That is not the meaning of "dynamic array". – Jim Garrison Feb 16 '17 at 23:11
  • Oh, okay. Thanks everyone. I thought it would add to the array whatever Int was entered, regardless of how many. – rahmor Feb 17 '17 at 01:47

2 Answers2

0
int[] array = new int[scan.nextInt()];

is equivalent to the following code snippet.

int size = scan.nextInt();
int[] array = new int[size];

The code snippet creates an array with the size given as an input by the user. You can check it by printing the length of the array.

System.out.println(array.length);
Wasi Ahmad
  • 27,225
  • 29
  • 85
  • 140
0
int[] array = new int[scan.nextInt()];

int - is the type of elements that will be contained within the array.

[ ] - indicates that it's an array.

array - reference to the array object.

new - creates the array object.

scan.nextInt() - scans the next token of the input as an int and sets the array length to that value.

Ousmane D.
  • 50,173
  • 8
  • 66
  • 103