-1

So you can declare an array in Java in two ways:

1.) The usual way:

int[] values = new int[3]; 
values[2] = 3; 

2.) The easier way:

int[] values = {2,3,4};

For more dimensions:

int[][] numbers = {{2,5,6},{10,76,52}}; 

So my questions are:

  • What is the name of technique number 2? How would I differenciate the two?

  • How can I extend technique number 2 to more that 2 dimensions?

Thank you for all your answers and I apologize if this question has been asked on SO already (in which case, kindly give me the link).

SDG
  • 2,260
  • 8
  • 35
  • 77
  • Your "more dimensions" is incorrect. re #2, if correct (don't forget the outer curly braces), perhaps initialize an array with literal values. – Hovercraft Full Of Eels Aug 20 '15 at 03:32
  • @HovercraftFullOfEels How so? – SDG Aug 20 '15 at 03:33
  • Try putting it in a program and the compiler will complain as you're forgetting the outer braces: `int[][] numbers = {{2, 5, 6}, {10, 76, 52}}; ` Regarding "extending number 2", just keep nesting curly braces. Try it and you'll find the solution I'll bet. – Hovercraft Full Of Eels Aug 20 '15 at 03:34
  • in java multidimensional arrays are just the array of arrays. A 3 dimensinal array is just an array whose elements are two dimensional arrays. for example: int a[][]={{1,2},{3,4}} and int b={{4,5},{6,7}}. So a three dimensional array can be created as int c[][][]={a,b}. – hermit Aug 20 '15 at 03:38

1 Answers1

2

Your second example is incorrect as posted. I think you wanted something like,

int[][] numbers = { { 2, 5, 6 }, { 10, 76, 52 } };

which should explain that it's an array of arrays. To add another dimension might be done like,

int[][][] numbers = { { { 2, 5, 6 }, { 10, 76, 52 } } };

And you can print both methods with Arrays.deepToString(Object[]) like

System.out.println(Arrays.deepToString(numbers));
Elliott Frisch
  • 198,278
  • 20
  • 158
  • 249