CS 231: Lab #2

Title image Spring 2018

2D Arrays

The goal of this lab period is to practice using 2D arrays in Java.


  1. Create a working directory for today's lab. Then start a Java file called Grid.java and make a public class called Grid.

  2. Create a main function in the Grid class. The args parameter of the main() function contains strings from the command line. Use a for loop to print out all of the elements of the args array. Then run your Grid class a few different times with additional strings on the command line. For example, try the following:

    $ java Grid 42 96 81 hut hut

  3. Declare two int variables in the main function, I'll call them yogi and booboo. Convert arguments 0 and 1 of the command line strings into integers and assign them to yogi and booboo. Given a string s, you can make the conversion using the Integer method parseInt():


  4. Create a 2D array of type String. I'll call it ranger.

    String[][] ranger;

    Start by allocating the 2D array in a single new statement, giving it yogi and booboo as the row and column sizes. Then try the alternative of allocating the row size and column size separately. Is there any value in the second method?

    Allocating a 2D grid of String references does not create any String objects; it creates only references/pointers to String objects. To create the actual objects, you have to go through every location in the grid and create the String object for it. Do that now and give each location in the grid a random character. Hint: the expression 'a' means the ascii value of the character 'a'.

  5. Print out the contents of the 2D array as a 2D grid using a nested for loop. Make it look nice. As part of the print process, print out the number of rows and columns in the grid, querying the array for its length. Hint: Test using the .length field of arrays to retrieve both the number of rows and the number of columns, try thinking of a 2D array as an "array of arrays."

When you are done with the lab, go ahead and get started on the current project.