allTwos
This problem tests your knowledge of declaring and instantiating two-dimensional arrays in java.
Complete the methodallTwos
, returns a 2x2 two-dimensional array containing all 2s as elements.
This method of creating and initializing a 2D array may show up in AP problems.
----------Notes------------
Recall the syntax for declaring and instantiating 2D arrays.
int[][] my2D = new int[row][col];
What if you wanted to initialize a small 2D array with values?
Do you remember how to initialize a 1D array with values during creation? Here's a reminder:
int[] my1D = {1, 2, 3};
Notice how each element of the 1D array is a literal int. You can do the same thing for 2D arrays! A 2D array can be thought of as a 1D array of arrays. If you're borrowing from the line of code above, instead of literal ints, you can then use the syntax for 1D arrays in their place.
type[][] my2D = { array1, array2, array3};
In the generic example above, you can then replace array1, array2, and array3 with actual 1D arrays.
Example:
//An array that contains two one-dimensional arrays of size 1!
int[][] oneByOne = { {1}, {1} } ;
//An array that contains two one-dimensional arrays of size 2!
int[][] twoByTwo = {
{1, 2},
{3, 4}
};
If we format it a little differently, you can then see how each 1D array makes up the rows! Check out unit 6 problems for the review!
You may need to review 1D array initialization if you're fuzzy on this syntax!