1

Let say I have the following field

private String[] myString;

and later on in the code fill this array with values from another array

String[] s = {"x", "y", "z"}; 

myString = s;

yes - that was very easy. No need to allocate memory with the new operator and specify the length in advance. But now - let say that myString has two dimensions:

private String[][] myString;

And I want to assign s to MyString. Is it possible to do it in a similar manner - in other words - without allocate memory and loop through the arrays.

(There should be only one column in myString[][] - this is because a constructor to another class demands that)

1
  • {{"a","b"},{"c","d"}} doesn't work? I thought it should. Commented Sep 18, 2014 at 19:53

4 Answers 4

1

Yes - you can have literals of two (or three, or ten, for that matter) dimensional arrays:

String[][] myString = { {"a", "b", "c"}, {"x", "y", "z"} };
Sign up to request clarification or add additional context in comments.

Comments

0

In Java, a two-dimensional array is simply an array of arrays. So you can do something like this

 String[][] myString = {{"x", "y", "z"}};

Comments

0

When you are declaring the variable along with initializing it, you can use braces similar to your 1D array example. The only difference is that you can nest the braces for multiple dimensions.

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

Comments

0

In simple words private String[][] myString is a 2D array and you have to define certain row and column to assign strings. This would be helpful private String[][] myString={s};

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.