• Post Reply Bookmark Topic Watch Topic
  • New Topic

initializing an array  RSS feed

 
Gino Fortunato
Greenhorn
Posts: 8
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
i know that will generate a 2x2 array

but I'm looking at a certification mock question and I see

What is the empty [] on the right hand side of the equal sign trying to tell me? Is there some default value?
 
Srinivasun Thoyyeti
Greenhorn
Posts: 6
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
"double [][] da = new double [3][] " - is a partial declaration of two 2D array;
Where in you are only aware of no of rows at declaration time;
and the no of columns you are supposed to know at run-time;
This declaration Gives you flexibility to have different column size for each row;

1D row array

Entry 1 ---> <missing columns 1-D array>

Entry 2 ---> <missing columns 1-D array>

Entry 3 ---> <missing columns 1-D array>

For example following is valid:
da[0] = new double[10];
da[1] = new double[5];
da[2] = new double[9];


 
Campbell Ritchie
Marshal
Posts: 56518
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Gino Fortunato wrote:i know that will generate a 2x2 array . . .
No, it won't.
 
Campbell Ritchie
Marshal
Posts: 56518
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Srinivasun Thoyyeti wrote: "double [][] da = new double [3][] " - is a partial declaration of two 2D array; . . .
No it isn't.

There is no such thing as a 2D array in Java®. Only 1D arrays.
This is what a 2D array would look like
int array[][] = ({1, 2}, {3, 4}}; memory = 1, 2, 3, 4 and that is bona fide C programming, not Java®.
What you have in Java® however is an array or arrays. The array consists of something like this:-
ClassFile, length, memberArray0, memberArray1. Each of those is a memory location.
Rather than having an array with two dimensions it is an array containing other ordinary 1D arrays. As ST correctly points out, you get more flexibility, but you get even more flexibility than that.
 
Campbell Ritchie
Marshal
Posts: 56518
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Srinivasun Thoyyeti wrote: . . .
1D row array

Entry 1 ---> <missing columns 1-D array>

Entry 2 ---> <missing columns 1-D array>

Entry 3 ---> <missing columns 1-D array>
. . .
Afraid not. You do not have numbers nor pointers to numbers in that array. You have pointers to other arrays. So what you actually have is this:-
Entry0→null
Entry1→null
Entry2→null
All is well until you try using those elements. If you don't assign them to something real, you get this sort of thingThat is why you should always fill arrays before trying to use them.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!