Ask the Expert

Defining a Java array

How do you define a Java array whose entries are also Java arrays?

    Requires Free Membership to View

The easiest method is to define a two-dimensional array and assign each member as follows:

// define two-dimensional array

    Object[][] objArr = new Object[5][3];

 

    // assign values to array

    for (int i = 0; i < objArr.length; i++)

    {

      objArr[i] = new Integer[3];

      for (int j = 0; j < objArr[i].length; j++)

      {

        objArr[i][j] = new Integer((i + 1) * (j + 5));

      }

    }

 

    // display results

    for (int i = 0; i < objArr.length; i++)

    {

      for (int j = 0; j < objArr[i].length; j++)

      {

        System.out.println("objArr[" + i + "][" + j + "] = " + objArr[i][j]);

      }

    }

This was first published in February 2005

There are Comments. Add yours.

 
TIP: Want to include a code block in your comment? Use <pre> or <code> tags around the desired text. Ex: <code>insert code</code>

REGISTER or login:

Forgot Password?
By submitting you agree to receive email from TechTarget and its partners. If you reside outside of the United States, you consent to having your personal data transferred to and processed in the United States. Privacy
Sort by: OldestNewest

Forgot Password?

No problem! Submit your e-mail address below. We'll send you an email containing your password.

Your password has been sent to: