Example - Printing a Picture

Contact Us or call 1-877-932-8228
Example - Printing a Picture

Example - Printing a Picture

This example uses a two-dimensional array preloaded with text characters that make up a picture

  • There is a loop that processes each row (the first, or most significant, dimension of the array, each element of which is an array of characters).
  • Within that loop, another loop prints each character without ending the line.
  • Then, when the inner loop is done, a newline is printed.

Code Sample:

Java-Arrays/Demos/ArrayPicture.java
public class ArrayPicture {
  public static void main(String[] args) {
    char[][] imgData = 
      new char[][] {
         { ' ',' ',' ',' ',' ',' ',' ' }, 
         { ' ',' ',' ','0',' ',' ',' ' }, 
         { ' ',' ',' ','|',' ',' ',' ' }, 
         { ' ','0','-','+','-','0',' ' }, 
         { ' ',' ',' ','|',' ',' ',' ' }, 
         { ' ',' ',' ','0',' ',' ',' ' },
         { ' ',' ',' ',' ',' ',' ',' ' }
       }; 
                                      
    for (int row = 0; row < imgData.length ; row++ ) {
      for (int col = 0; col < imgData[row].length; col++ ) {
        System.out.print(imgData[row][col]);
      }
      System.out.println();
    }
  }
}

Because multi-dimensional arrays are implemented as arrays of array references, it is possible to partially instantiate an array:

int[][] nums = new int[3][];

This creates nums as a two-dimensional array (better viewed in this case as an array of array references), and creates an array holding three null references to integer arrays

Two-dimensional array instantiated with only the row dimension populated

Next