unit 8 Flashcards
(25 cards)
What is a 2D array in Java?
An array of arrays; a table with rows and columns.
How do you declare a 2D array?
dataType[][] arrayName;
How do you create a 2D int array with 3 rows and 4 columns?
new int[3][4];
How do you access an element in a 2D array?
arrayName[row][col];
How do you set an element in a 2D array?
arrayName[row][col] = value;
What does array.length return for a 2D array?
The number of rows.
How do you find the number of columns in a 2D array?
arrayName[row].length
Can each row of a 2D array have a different length?
Yes
How do you traverse a 2D array?
Nested for loops: outer loop for rows
Write a basic 2D array traversal.
for (int r = 0; r < arr.length; r++) { for (int c = 0; c < arr[r].length; c++) { arr[r][c]; }}
What is row-major order traversal?
Visiting all elements row by row (row first
What is column-major order traversal?
Visiting all elements column by column (column first
How do you initialize a 2D array with values?
int[][] arr = {{1
What happens if you access an invalid index in a 2D array?
ArrayIndexOutOfBoundsException
How do you sum all elements in a 2D array?
Use nested loops and add each element.
How do you find the maximum value in a 2D array?
Initialize max
What is a practical use of 2D arrays?
Storing grids
What is the difference between arr.length and arr[0].length?
arr.length is number of rows
How can you print a 2D array neatly?
Use nested loops with System.out.print and newline at end of each row.
How can you reverse rows in a 2D array?
Swap elements in each row moving inward.
What should you always check before accessing arr[r][c]?
Ensure 0 <= r < arr.length and 0 <= c < arr[r].length
How do you count a certain value in a 2D array?
Use nested loops and an if-statement.
What happens when you assign one 2D array to another?
They both reference the same array object (aliasing).
How do you create a deep copy of a 2D array?
Create a new array and copy each row manually.