Java: how to initialize String[]?

后端 未结 11 2185
渐次进展
渐次进展 2020-12-22 18:57

Error

% javac  StringTest.java 
StringTest.java:4: variable errorSoon might not have been initialized
        errorSoon[0] = \"Error, why?\"         


        
11条回答
  •  一生所求
    2020-12-22 19:13

    You need to initialize errorSoon, as indicated by the error message, you have only declared it.

    String[] errorSoon;                   // <--declared statement
    String[] errorSoon = new String[100]; // <--initialized statement
    

    You need to initialize the array so it can allocate the correct memory storage for the String elements before you can start setting the index.

    If you only declare the array (as you did) there is no memory allocated for the String elements, but only a reference handle to errorSoon, and will throw an error when you try to initialize a variable at any index.

    As a side note, you could also initialize the String array inside braces, { } as so,

    String[] errorSoon = {"Hello", "World"};
    

    which is equivalent to

    String[] errorSoon = new String[2];
    errorSoon[0] = "Hello";
    errorSoon[1] = "World";
    

提交回复
热议问题