Printing a 2D Array

Classic programmed-learning exercises, refreshed for modern Java and presented in the current MrStyner.com portfolio style.

Modern Java noteThis archive has been refreshed for Java 25 LTS. Core language concepts remain useful, while outdated setup instructions and browser-era Java are labeled or replaced. Java 26 is the current feature release; Java 25 is used here as the stable teaching baseline.
go to previous page   go to home page   go to next page

Answer:

  • How many rows must be printed?
    • 3
  • How many cells in each row must be printed?
    • 3 for row 0
    • 2 for row 1
    • 5 for row 3

Printing a 2D Array

Here is a program that creates a 2D array, then prints it out.

The way that the nested loops are written enable the program to print out the correct number of cells for each row. The expression uneven[row].length evaluates to a different integer for each row of the array.



RowCol
01234
0 1 9 4

1 0 2

2 0 1 2 3 4
uneven
class unevenExample3 { public static void main( String[] arg ) { // declare and construct a 2D array int[][] uneven = { { 1, 9, 4 }, { 0, 2}, { 0, 1, 2, 3, 4 } }; // print out the array for ( int row=0; row < uneven.length; row++ ) { System.out.print("Row " + row + ": "); for ( int col=0; col < uneven[row].length; col++ ) System.out.print( uneven[row][col] + " "); System.out.println(); } } }

QUESTION 14:

For the print method to work, must every row of uneven be non-null?