Skip to content
Fix Code Error

Java: how to initialize String[]?

March 13, 2021 by Code Error
Posted By: Anonymous

Error

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

Code

public class StringTest {
        public static void main(String[] args) {
                String[] errorSoon;
                errorSoon[0] = "Error, why?";
        }
}

Solution

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";
Answered By: Anonymous

Related Articles

  • What is and how to fix System.TypeInitializationException…
  • How to allocate aligned memory only using the standard…
  • Creating an dynamic array, but getting segmentation fault as…
  • TLS 1.3 server socket with Java 11 and self-signed…
  • Virtual Memory Usage from Java under Linux, too much memory…
  • GLYPHICONS - bootstrap icon font hex value
  • The static keyword and its various uses in C++
  • VUE Error when run test unit
  • Eclipse will not start and I haven't changed anything
  • What is a NullReferenceException, and how do I fix it?

Disclaimer: This content is shared under creative common license cc-by-sa 3.0. It is generated from StackExchange Website Network.

Post navigation

Previous Post:

How to check whether a string contains a substring in Ruby

Next Post:

Excel to CSV with UTF8 encoding

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

  • Get code errors & solutions at akashmittal.com
© 2022 Fix Code Error