2 Dimensional (2D) Arrays


Java, as with most languages, supports multi-dimensional arrays. This note covers  2 Dimensional (2D) Arrays. Two-dimensional arrays are usually visualized as a matrix, with rows and columns. So the following array declaration contains five rows and four columns. i.e., a 5×4 array.

Object[][] data = {
 {"Kathy", "Smith", "Snowboarding", new Integer(1081)},
 {"John", "Doe", "Rowing", new Integer(805)},
 {"Sue", "Black", "Knitting", new Integer(1095)},
 {"Jane", "White", "Speed reading", new Integer(1639)},
 {"Joe", "Brown", "Pool", new Integer(1018)}

To see what’s in the array, use the code:

for (int row = 0; row < data.length; row++) {
   System.out.printf("Person# %d%n", (row+1));
   for (int col = 0; col < data[row].length; col++) {

Another way of creating and populating arrays can be done this way.

Object[][] newdata = new Object[2][4];

This array has two rows and four columns.

Create two 1D arrays:

Object[] new_person1 = {"George", "Black", "Writer", new Integer(341659)};
Object[] new_person2 = {"Abigail", "Garcia", "Pharmacist", new Integer(549171)};

So we now have two people to put in our newdata array which we can do this way:

newdata[0] = new_person1;
newdata[1] = new_person2;

Again, using the code:

for (int row = 0; row < newdata.length; row++) {
   System.out.printf("Person# %d%n", (row+1));
   for (int col = 0; col < newdata[row].length; col++) {

should show what we now have in the array.

See also

The Java Language Specification, Chapter 10. Arrays

The Java Tutorials. The Java Tutorials are practical guides for programmers who want to use the Java programming language to create applications. They include hundreds of complete, working examples, and dozens of lessons. Groups of related lessons are organized into “trails”.

Java Platform, Standard Edition (Java SE) resources.

This entry was posted in java and tagged , . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s