Have Array Brackets, Will Travel

There is a quirk of syntax in that the array declaration bracket pairs can “float” to be next to the element type, to be next to the data name, or to be in a mixture of the two. The following are all valid array declarations:

int a [] ;
int [] b = { 5, 2, 3 } ;

char c [][] = new char[12][31];
char[] d [] = { {1,1,1,1}, {2,2,2,2} }; // creates d[2][4]
char[][] e;

byte f [][][] = new byte [3][3][7];
byte [][] g[] = new byte [3][3][7];

short [] h, i[], j, k[][];

If array brackets appear next to the type, they are part of the type, and apply to every variable in that declaration. In the code above, “j” is an array of short, and “i” is an array of arrays of short. If the array brackets are next to the variable name, they apply only to that variable name.

Allowing (encouraging, actually) array brackets next to the type name is done so declarations of functions returning arrays can be read more easily. Here is an example of how returning an array value from a function would look following C rules. (You can't return an array in C, but this is how C syntax would express it if you could.)


int funarray()[] { ... }                       Pseudo-C code

Here are the alternatives for expressing it in Java (and it is permissible in Java), first following the C paradigm:


int ginger ()[] { return new int[20]; }       Java code

A much better way is to express it as shown in Figure 9-1.

Figure 9-1. Better array declaration

image

Figure 9-1 allows the programmer to see all the tokens that compose the return type grouped together.

Chapter 10 has an explanation of what the stack and heap do for you. In some languages the stack lets you get into trouble by re-using memory that is already in use somewhere else in your program. Arrays are never allocated on the stack in Java, so you cannot get into trouble this way (see Chapter 10 for the full story). The takeaway here is that Java closes a loophole that's a big source of bugs in C/C++.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.222.167.183