Java Reference
In-Depth Information
accessed simply via the index. The following code prompts the user to enter a month
number and displays its month name:
String[] months = {
"January"
,
"February"
, ...,
"December"
};
System.out.print(
"Enter a month number (1 to 12): "
);
int
monthNumber = input.nextInt();
System.out.println(
"The month is "
+ months[monthNumber -
1
]);
If you didn't use the
months
array, you would have to determine the month name using
a lengthy multi-way
if-else
statement as follows:
if
(monthNumber ==
1
)
System.out.println(
"The month is January"
);
else if
(monthNumber ==
2
)
System.out.println(
"The month is February"
);
...
else
System.out.println(
"The month is December"
);
7.2.7 Foreach Loops
Java supports a convenient
for
loop, known as a
foreach loop
, which enables you to traverse
the array sequentially without using an index variable. For example, the following code dis-
plays all the elements in the array
myList
:
for
(
double
e: myList) {
System.out.println(e);
}
You can read the code as βfor each element
e
in
myList
, do the following.β Note that the
variable,
e
, must be declared as the same type as the elements in
myList
.
In general, the syntax for a foreach loop is
for
(elementType element: arrayRefVar) {
// Process the element
}
You still have to use an index variable if you wish to traverse the array in a different order or
change the elements in the array.
Caution
Accessing an array out of bounds is a common programming error that throws a runtime
ArrayIndexOutOfBoundsException
. To avoid it, make sure that you do not use
an index beyond
arrayRefVar.length - 1
.
Programmers often mistakenly reference the first element in an array with index
1
, but
it should be
0
. This is called the
off-by-one error
. Another common off-by-one error in
a loop is using
<=
where
<
should be used. For example, the following loop is wrong.
ArrayIndexOutOfBounds-
Exception
off-by-one error
for
(
int
i =
0
; i <= list.length; i++)
System.out.print(list[i] +
" "
);
The
<=
should be replaced by
<
.
7.1
β
β
How do you declare an array reference variable and how do you create an array?
Check
7.2
When is the memory allocated for an array?
Point
Search WWH ::
Custom Search