Java Reference
In-Depth Information
In that case, the size of the array is
deduced
from the number of elements in
the set, and should therefore not be explicitly specified. Nor shall there be an
explicit creation using the keyword
new
. Here are a few examples illustrating
static array declarations, creations and initializations. Arrays can be declared
within the body of a function or globally as a static variable of the class. To
illustrate global static arrays, consider the following program:
Program 4.1
Static array declarations and creations
class
ArrayDeclaration
{
static int
digit [] =
{
1, 2, 3, 4, 5, 6, 7, 8, 9, 0
}
;
static double
x[]=
{
Math . PI , Math . E, 1 . 0 , 0 . 0
}
;
static boolean
prime[]=
{
false
,
true
,
true
,
true
,
false
,
true
,
false
,
true
,
false
,
false
}
;
static int
y[];
static void
MyFunction(
int
n)
{
// Allocate an array of size n
y=
new i n t
[2
∗
n];
}
public static void
main ( String [ ]
args )
{
MyFunction (15) ;
// We recreate and initialize array y;
MyFunction (20) ;
}
}
Observe that in this sample program, array
y
is created twice. In any case,
arrays are allocated and stored in the global memory, and not stored in the
local function call stack. Only the references of arrays are stored in the function
stack for arrays declared within functions (without the keyword
static
).
4.2.3 Retrieving the size of arrays:
length
Arrays in Java carry additional information
1
about themselves: Their types and
lengths. The size of an array
array
is accessed by using the keyword
length
,
post-appended to the array name with a “.” dot:
array.length
Observe that there are no parenthesis used in conjunction with the keyword
length
.
static boolean
prime[]=
{
false
,
true
,
true
,
true
,
false
,
true
,
false
,
true
,
false
,
false
}
;
1
Technically speaking, we say that arrays in Java are reflexive since they contain
additional information. This is to contrast with arrays in C or C++ that are
non-
reflexive
since they contain only their components.
Search WWH ::
Custom Search