Hi I am trying to initialize 4 string arrays of length 10,100,1000,10000 and these arrays are like
array1={\"0\",\"1\",...\"9\"}
array2={\"00\",\"01\",...\
Constant array in are initialized in java bytecode by loading each value from the constant pool and assigning it to the corresponding array index. This takes several bytes of code per array element. The size of a jvm method is limited to 65535 bytes since its length is stored in the class file using a 16 bit number.
In the case where the values can not be easily calculated in a loop, you could break the initialization into separate static functions:
static {
array1 = getValuesForArray1();
...
}
private static String[] getValuesForArray1() {
...
}
If there is a pattern to the initialization values its of course better to calculate the values on the fly.
Use for
loops. For example:
for (int i = 0; i <= 9; i++)
array1[i] = String.valueOf(i);
It maybe better solved by writing a method that takes an int argument and returns the string value that would have been at that array index. Here it is using String.format and specifying the left padding length:
private static String getValue(int index, int stringLength) {
return String.format("%0" + stringLength + "d", index);
}