The cliche of array initialization in java

  • 2020-07-21 07:36:19
  • OfStack

Arrays can be initialized in two ways:

1. Static initialization

2. Dynamic initialization

Static initialization:

Ex. :


String[] str = new String[]{"A","B","C"};
String str[] = new String[]{"A","B","C"};
String str = {"A","B","C"};

Dynamic initialization:

Ex. :


String[] srt = new String[3];
srt[0] = "A";
srt[1] = "B";
srt[2] = "C";

Note: Not simultaneously

Use both static and dynamic initializers, which means that you should not specify both the length of the array and the value of the array elements when the array is initialized.

But the code under 1 is executable


String str[] = {"A","B","C"};
str = new String[3];

But the reverse is not possible, because this way is to redirect str to another memory address, and {"A","B","C"} is static initialization can not be executed after array initialization.


Related articles: