Java two dimensional (2d) array examples

It's been so long since I create a two-dimensional Java array in I almost couldn't remember how to do it. Fortunately I did, and I thought I'd include my sample code here in case it will help anyone else.

So, in this quick tutorial, I'll show you how to create a two-dimensional array (2D array) of Java String objects, and then I'll show you how to access each element in the array.

How to create a two-dimensional Java array

First, here's how I create the two-dimensional arrays of strings with this code:

String[][] data = {
    {"debug/Authentication", "/root/opensso/opensso/debug/Authentication"},
    {"debug/CoreSystem", "/root/opensso/opensso/debug/CoreSystem"},
    {"debug/Policy", "/root/opensso/opensso/debug/Policy"},
    {"debug/Session", "/root/opensso/opensso/debug/Session"},
    {"log/amAuthentication.access", "/root/opensso/opensso/log/amAuthentication.access"},
    {"log/amAuthentication.error", "/root/opensso/opensso/log/amAuthentication.error"},
    {"log/amConsole.access", "/root/opensso/opensso/log/amConsole.access"},
    {"log/amConsole.error", "/root/opensso/opensso/log/amConsole.error"},
    {"log/amPolicy.access", "/root/opensso/opensso/log/amPolicy.access"},
    {"log/amPolicy.error", "/root/opensso/opensso/log/amPolicy.error"},
    {"log/amSSO.access", "/root/opensso/opensso/log/amSSO.access"},
    };

As you can see, with a static array like this it's pretty straightforward, and similar to other languages.

How to access elements in the two-dimensional array

Next, here's how I use this 2D Java array, first getting the array length, then looping through each element in the 2D array:

int numRows = data.length;
for (int i=0; i< numRows; i++)
{
  logfile = new Logfile(data[i][0], server, 5556, data[i][1], command);
  logfiles.add(logfile);
}

For the purposes of this tutorial it doesn't matter what a Logfile object is, just see how I'm accessing the 2D array named data in this line:

logfile = new Logfile(data[i][0], server, 5556, data[i][1], command);

In this loop, I first access array element, data[0][1], then data[1][1], then data[2][1], etc.

Some other situations may be more complex, and you may need to iterate through the array with two nested for loops, but for my purposes this worked just fine.

Post new comment

The content of this field is kept private and will not be shown publicly.