Java - How do I make a String array with values?
You could do something like this
String[] myStrings = { "One", "Two", "Three" };
or in expression
functionCall(new String[] { "One", "Two", "Three" });
or
String myStrings[];
myStrings = new String[] { "One", "Two", "Three" };
By using the array initializer list syntax, ie:
String myArray[] = { "one", "two", "three" };
Another way to create an array with String apart from
String[] strings = { "abc", "def", "hij", "xyz" };
is to use split. I find this more readable if there are lots of Strings.
String[] strings = "abc,def,hij,xyz".split(",");
or the following is good if you are parsing lines of strings from another source.
String[] strings = ("abc\n" +
"def\n" +
"hij\n" +
"xyz").split("\n");
Another way is with Arrays.setAll
, or Arrays.fill
:
String[] v = new String[1000];
Arrays.setAll(v, i -> Integer.toString(i * 30));
//v => ["0", "30", "60", "90"... ]
Arrays.fill(v, "initial value");
//v => ["initial value", "initial value"... ]
This is more usefull for initializing (possibly large) arrays where you can compute each element from its index.