10.5
Arrays: A Simple Example
ARRAYS
10.5 Arrays: A Simple Example
The example:
class Gauss {
public static void main(String[] args) {
int[] ia = new int[101];
for (int i = 0; i < ia.length; i++)
ia[i] = i;
int sum = 0;
for (int i = 0; i < ia.length; i++)
sum += ia[i];
System.out.println(sum);
}
}
that produces output:
5050
declares a variable
ia
that has type array of
int
, that is,
int[]
. The variable
ia
is
initialized to reference a newly created array object, created by an array creation
expression ( 15.9). The array creation expression specifies that the array should
have
101
components. The length of the array is available using the field
length
,
as shown.
The example program fills the array with the integers from
0
to
100
, sums
these integers, and prints the result.
10.6 Arrays Initializers
An
array initializer
may be specified in a declaration, creating an array and pro
viding some initial values:
ArrayInitializer:
{
VariableInitializers
opt
,
opt
}
VariableInitializers:
VariableInitializer
VariableInitializers
,
VariableInitializer
The following is repeated from 8.3 to make the presentation here clearer:
VariableInitializer:
Expression
ArrayInitializer
196
footer
Our partners:
PHP: Hypertext Preprocessor Best Web Hosting
Java Web Hosting
Inexpensive Web Hosting
Jsp Web Hosting
Cheapest Web Hosting
Jsp Hosting
Cheap Hosting
Visionwebhosting.net Business web hosting division of Web
Design Plus. All rights reserved