Java Reference
In-Depth Information
Chapter 15
Arrays
In this chapter, you will learn:
•
How to declare array variables
•
How to create arrays
•
How to access elements of an array
for
loop and a
for
-
each
loop to iterate through elements an array
•
How to use a
•
How to copy elements of one array to another array
•
How to copy primitive and reference types arrays
•
How to use multi-dimensional arrays
ArrayList
when a variable-length array is needed
•
How to use an
ArrayList
to an array and vice versa
•
How to convert elements of an
What Is an Array?
An array is a fixed-length data structure that is used to hold more than one value of the same data type. Let's consider
an example, which will explain why we need arrays. Suppose you have been asked to declare variables to hold
employee ids of three employees. The employee ids will be integers. The variable declarations to hold three integer
values will look like
int empId1, empId2, empId3;
What do you do if the number of employees increases to five? You may modify your variable declarations to
look like
int empId1, empId2, empId3, empId4, empId5;
What do you do if the number of employees increases to 1,000? You definitely would not want to declare
1,000
int
variables like
empId1
,
empId2...empId1000
. Even if you do that, the resulting code would be unmanageable
and clumsy. Arrays come to your rescue in such situations. Using an array, you can declare a variable of a type, which
can hold as many values of that type as you want. In fact, Java has a restriction on the number of values an array can
hold. An array can hold a maximum of 2,147,483,647 values, which is the maximum value of the
int
data type.