devxlogo

java (arrays)

java (arrays)

Question:
How do you create and use a multidimensional array of type int.

Answer:
C programmers are used to dealing with multidimensional arrays as chunksof contiguous memory which can be accessed through pointer arithmetic.In Java, an array is an actual object, and a multidimensional arraymust be constructed as a an array of arrays. It is an extremely convenientarrangement because you can access the length of an array from withinthe Java language, which allows you to make each array of a differentlength if necessary, without causing undue complications. But thedownside is that you must explicitly instantiate each array, which is notas efficient as allocating one big chunk of memory. To create a 3x3x3array of integers you would do the following:

public final class Matrix {  public static final void main(String[] args) {    int i, j;    int[][] matrix[];    matrix = new int[3][][];    for(i = 0; i < matrix.length; i++) {      matrix[i] = new int[3][];      for(j = 0; j < matrix[i].length; j++)	matrix[i][j] = new int[3];    }  }}
See also  Redefining Energy Management: Advanced Solutions for Modern Buildings
devxblackblue

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist