Java: how to initialize String[]?
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";
How do I declare and initialize an array in Java?
You can either use array declaration or array literal (but only when you declare and affect the variable right away, array literals cannot be used for re-assigning an array).
For primitive types:
int[] myIntArray = new int[3]; // each element of the array is initialised to 0
int[] myIntArray = {1, 2, 3};
int[] myIntArray = new int[]{1, 2, 3};
// Since Java 8. Doc of IntStream: https://docs.oracle.com/javase/8/docs/api/java/util/stream/IntStream.html
int [] myIntArray = IntStream.range(0, 100).toArray(); // From 0 to 99
int [] myIntArray = IntStream.rangeClosed(0, 100).toArray(); // From 0 to 100
int [] myIntArray = IntStream.of(12,25,36,85,28,96,47).toArray(); // The order is preserved.
int [] myIntArray = IntStream.of(12,25,36,85,28,96,47).sorted().toArray(); // Sort
For classes, for example String
, it's the same:
String[] myStringArray = new String[3]; // each element is initialised to null
String[] myStringArray = {"a", "b", "c"};
String[] myStringArray = new String[]{"a", "b", "c"};
The third way of initializing is useful when you declare an array first and then initialize it, pass an array as a function argument, or return an array. The explicit type is required.
String[] myStringArray;
myStringArray = new String[]{"a", "b", "c"};
Initialize part of an array in java
You can do something like this, it will create array with new size based on provided.
String[] temp = new String[] {"water", "shovel", "berries", "stick", "stone", "seed", "axe"};
String[] val = Arrays.copyOf(temp, 20);
System.out.println(val.length);
System.out.println(Arrays.toString(val));
The output will be:
20
[water, shovel, berries, stick, stone, seed, axe, null, null, null, null, null, null, null, null, null, null, null, null, null]
How to Create and Initialize (in Java) a ListString[] in the same statement? (Editors please NOTE: this *not* the same as just a ListString)
The correct answer was given in the comments (above) by @user16320675 , and this works well. It handles both the creation of the outer List and the internal array of strings. Other answers pointing to a simple Array asList are for simple strings, which is not the question that was asked.
to create a mutable list
final List<String[]> rolesCsv =
new ArrayList<String[]>Collections.singletonList(new String[]{"Role Name","Description"}));
Otherwise (despite the array, its element, will not be immutable)
final List<String[]> rolesCsv =
Collections.singletonList(new String[]{"Role Name","Description"})
How can I initialization String array set null in java?
Assuming that you want array like
String[] arr = {"foo", "bar"};
to become
[null, null]
and do it in one line, then you can use
Arrays.fill(arr, null);
or create new array with same size as previous one
arr = new String[arr.length];
Declare a private String array and initialization of array elements giving an error
You need an initialization block to do that, like
private String[] phoneNumber = new String[3];
{
phoneNumber[0] = "hi";
phoneNumber[1] = "hello";
phoneNumber[2] = "hola";
}
or use the shorter array literal syntax. Like,
private String[] phoneNumber = { "hi", "hello", "hola" };
Related Topics
Installing Java on Os X 10.9 (Mavericks)
JSON Gson.Fromjson Java Objects
Logging User Activity in Web App
Why Is System.Arraycopy Native in Java
How to Convert a Binary String to a Base 10 Integer in Java
Generate JPA 2 Entities from Existing Database
Is There Any Good and Free Date and Time Picker Available for Java Swing
How to Call Super Constructor in Lombok
Nosuchmethoderror on Startup in Java Jersey App
Download Large File from Server Using Rest Template Java Spring MVC
Using Eclipse Java Compiler (Ecj) in Maven Builds
Extract Source Code from .Jar File
In Java, How to Define an Integer Constant in Binary Format
Does Java Have Any Mechanism for a Vm to Trace Method Calls on Itself, Without Using Javaagent, etc
"Noclassdeffounderror: Could Not Initialize Class" Error
How to Hide a Jframe in System Tray of Taskbar
How to Set a Long Java Classpath in Windows
How Do Java Method Annotations Work in Conjunction with Method Overriding