AP CSA String Manipulation and 2D Arrays 2 — Questions and Answers
Question 1: What does `str.toUpperCase()` do?
- Returns a new String with all characters converted to uppercase (Correct answer)
- Modifies the original String in place
- Converts only the first character to uppercase
- Throws an exception if numbers are present
Correct answer: Returns a new String with all characters converted to uppercase
toUpperCase() returns a new String with all alphabetic characters converted to uppercase; Strings in Java are immutable so the original is unchanged.
Question 2: How do you access the element in row 2, column 3 of a 2D array called `grid`?
- grid[2][3] (Correct answer)
- grid[3][2]
- grid(2,3)
- grid.get(2,3)
Correct answer: grid[2][3]
2D array elements are accessed with [row][column] syntax; grid[2][3] accesses row 2 (third row), column 3 (fourth column).
Question 3: What nested loop structure traverses all elements of a 2D array `int[][] m` with r rows and c columns?
- for(int i=0;i<m.length;i++) for(int j=0;j<m[i].length;j++) (Correct answer)
- for(int i=0;i<m[0].length;i++) for(int j=0;j<m.length;j++)
- for(int i=0;i<=m.length;i++) for(int j=0;j<=m[i].length;j++)
- for(int i=1;i<m.length;i++) for(int j=1;j<m[i].length;j++)
Correct answer: for(int i=0;i<m.length;i++) for(int j=0;j<m[i].length;j++)
The outer loop uses m.length for rows and the inner loop uses m[i].length for columns, correctly visiting every element.
Question 4: What does `str.substring(3)` return for `str = "JavaCode"`?
- "aCode" (Correct answer)
- "Jav"
- "Java"
- "Code"
Correct answer: "aCode"
substring(3) returns all characters from index 3 to the end; J(0),a(1),v(2),a(3)Code → "aCode".
Question 5: What is the result of `"5" + 3 + 2` in Java?
- "532" (Correct answer)
- 10
- "10"
- "53"
Correct answer: "532"
Java evaluates left to right: "5"+3 is String concatenation giving "53", then "53"+2 gives "532" — not arithmetic.
Question 6: How do you fill an entire 2D array `grid` of size n×m with the value 0?
- Use nested for loops assigning grid[i][j] = 0
- Use Arrays.fill(grid, 0)
- Use grid.fill(0)
- Declare it as `int[][] grid = new int[n][m]` (auto-initialized to 0) (Correct answer)
Correct answer: Declare it as `int[][] grid = new int[n][m]` (auto-initialized to 0)
Java automatically initializes int array elements to 0, so `new int[n][m]` creates a 2D array already filled with zeros.
What does `str.toUpperCase()` do?