• support@answerspoint.com

How to declare array in Java?

2004

How to declare array in Java?

2Answer


0

You can either use array declaration or array literal (but only when you declare and affect the variable right away, array literals cannot be used for re-assigning an array).

For primitive types:

int[] myIntArray = new int[3];
int[] myIntArray = {1,2,3};
int[] myIntArray = new int[]{1,2,3};

For classes, for example String, it's the same:

String[] myStringArray = new String[3];
String[] myStringArray = {"a","b","c"};
String[] myStringArray = new String[]{"a","b","c"};
  • answered 8 years ago
  • Gul Hafiz

0

There are two types of array.

One Dimensional Array

Syntax for default values:

int[] num = new int[5];

Or (less preferred)

int num[] = new int[5];

Syntax with values given (variable/field initialization):

int[] num = {1,2,3,4,5};

Or (less preferred)

int num[] = {1, 2, 3, 4, 5};

Note: For convenience int[] num is preferable because it clearly tells that you are talking here about array. Otherwise no difference. Not at all.

Multidimensional array

Declaration

int[][] num = new int[5][2];

Or

int num[][] = new int[5][2];

Or

int[] num[] = new int[5][2];

Initialization

 num[0][0]=1;
 num[0][1]=2;
 num[1][0]=1;
 num[1][1]=2;
 num[2][0]=1;
 num[2][1]=2;
 num[3][0]=1;
 num[3][1]=2;
 num[4][0]=1;
 num[4][1]=2;

Or

 int[][] num={ {1,2}, {1,2}, {1,2}, {1,2}, {1,2} };

Ragged Array (or Non-rectangular Array)

 int[][] num = new int[5][];
 num[0] = new int[1];
 num[1] = new int[5];
 num[2] = new int[2];
 num[3] = new int[3];

So here we are defining columns explicitly.
Another Way:

int[][] num={ {1}, {1,2}, {1,2,3,4,5}, {1,2}, {1,2,3} };

For Accessing:

for (int i=0; i<(num.length); i++ ) {
    for (int j=0;j<num[i].length;j++)
        System.out.println(num[i][j]);
}

Alternatively:

for (int[] a : num) {
  for (int i : a) {
    System.out.println(i);
  }
}

Ragged arrays are multidimensional arrays.
For explanation see multidimensional array detail at the official java tutorials

  • answered 8 years ago
  • Sunny Solu

Your Answer

    Facebook Share        
       
  • asked 9 years ago
  • viewed 2004 times
  • active 9 years ago

Best Rated Questions