84

I know how to make an empty array, but how do I make a String array with values from the start?

5 Answers 5

169

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" };
Sign up to request clarification or add additional context in comments.

4 Comments

Or String[] a = { "a", "b", "c" };, since the OP has asked specifically about Strings.
Not really what I was looking for. I want to make an array with strings.
Yes, I see the tag now. Strings not mentioned in the question, though. Thanks for update.
for completness, you should also add return new String[] {"one", "two"};
7

By using the array initializer list syntax, ie:

String myArray[] = { "one", "two", "three" };

Comments

6

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.

Comments

5

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");

Comments

2

You want to initialize an array. (For more info - Tutorial)

int []ar={11,22,33};

String []stringAr={"One","Two","Three"};

From the JLS

The [] may appear as part of the type at the beginning of the declaration, or as part of the declarator for a particular variable, or both, as in this example:

byte[] rowvector, colvector, matrix[];

This declaration is equivalent to:

byte rowvector[], colvector[], matrix[][];

2 Comments

+1 for the link to the tutorial but he did ask about Strings, in a roundabout sort of way (tagged it with "string").
I don't think I've ever seen anyone put the [] right at the start of the variable name, that looks funny.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.