Java: how to initialize String[]?
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?";
}
}
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";
String[] args = new String[]{"firstarg", "secondarg", "thirdarg"};
String[] errorSoon = { "foo", "bar" };
-- or --
String[] errorSoon = new String[2];
errorSoon[0] = "foo";
errorSoon[1] = "bar";
In Java 8 we can also make use of streams e.g.
String[] strings = Stream.of("First", "Second", "Third").toArray(String[]::new);
In case we already have a list of strings (stringList
) then we can collect into string array as:
String[] strings = stringList.stream().toArray(String[]::new);
I believe you just migrated from C++, Well in java you have to initialize a data type(other then primitive types and String is not a considered as a primitive type in java ) to use them as according to their specifications if you don't then its just like an empty reference variable (much like a pointer in the context of C++).
public class StringTest {
public static void main(String[] args) {
String[] errorSoon = new String[100];
errorSoon[0] = "Error, why?";
//another approach would be direct initialization
String[] errorsoon = {"Error , why?"};
}
}