Java Basics: Arrays

A chess board may be 8×8, but a two-dimensional array can be any size!

I think it would be a tragic statement of the universe if Java was the last language that swept through.

— James Gosling, founder of Java programming language.

A Java array is typically a collection of same data types which have a united memory location. We can store only a fixed set of data types in a Java array, but we can create/use an index to move through an array, as a wheel on a road. The first element of the array is stored at the 0th index, 2nd element is stored on 1st index and so on.

Chess is a board game with 8×8 squares. From left to right on the player’s side the closest row has: a Rook, a Knight, a Bishop, the Queen, the King, a Bishop, a Knight, and a Rook. The second-closest row has only Pawns, the most populous player piece.

Arrays by dimensions must be programmed differently. A one-dimensional array and a two-dimensional array differ in complexity. Observe:

String[] chessRow = new String[8]
String[][] chessGrid = new String[8][8]; // chessGrid strings represent pieces on the first and last rows of the board.

Our string, chessRow, is made up of a single row of 8. It’s important when setting up an array for it to be its number (rather not its number minus one) when being initialized because not doing so will flip the chess board and crash Java. After initialization, know that the first array element is in slot 0. To progress through it requires creating an index that loops iterating through it.

Our second string, chessGrid, is made up of two rows of 8. To progress through this two-dimensional array requires nested two looping iterators. Observe:

for (int y = 0; y < 8; y++) {
      for (int x = 0; x < 8; x++) {
            if ((y == 0)||(y == 7)) { // already initialized
                  }
            else if (y == 1) {
                    chessGrid[y][x] = "Black Pawn";
                  }
            else if (y == 6) {
                    chessGrid[y][x] = "White Pawn";
                  }
            else {
                  chessGrid[y][x] = "None";
                  }
            }
      }

The primary (first) for loop contains “vertical” piece movement, beginning at 0 or Black Rook. The secondary for loop contains “horizontal” piece movement, beginning at 0 also Black Rook. The else if statements reflect scanning starting Pawns adjacent to the main pieces at both ends of the Chess board.

And that’s how a two-dimensional array can simulate reading a Chess board, with a grid! While there can be more than two dimensions in an array, I’m not going there in this blog, here in Java programming or in Chess!

Strato Chess, taking Chess to another dimension!

Follow my original code on my GitHub profile!
Credit to my partner William Clark for his help!

Join the Conversation

  1. Unknown's avatar

1 Comment

Leave a comment

Design a site like this with WordPress.com
Get started