Friday, September 12, 2008

arrays in java

Arrays
An array is a group of like-typed variables that are referred to by a common name. Arrays
of any type can be created and may have one or more dimensions. A specific element in
an array is accessed by its index. Arrays offer a convenient means of grouping related
information.
Note If you are familiar with C/C++, be careful. Arrays in Java work differently than
they do in those languages.
One-Dimensional Arrays
A one-dimensional array is, essentially, a list of like-typed variables. To create an array,
you first must create an array variable of the desired type. The general form of a onedimensional
array declaration is
type var-name[ ];
Here, type declares the base type of the array. The base type determines the data type of
each element that comprises the array. Thus, the base type for the array determines
what type of data the array will hold. For example, the following declares an array named
month_days with the type "array of int":
int month_days[];
Although this declaration establishes the fact that month_days is an array variable, no
array actually exists. In fact, the value of month_days is set to null, which represents an
array with no value. To link month_days with an actual, physical array of integers, you
must allocate one using new and assign it to month_days. new is a special operator that
allocates memory.
You will look more closely at new in a later chapter, but you need to use it now to allocate
memory for arrays. The general form of new as it applies to one-dimensional arrays
appears as follows:
array-var = new type[size];
Here, type specifies the type of data being allocated, size specifies the number of
elements in the array, and array-var is the array variable that is linked to the array. That
is, to use new to allocate an array, you must specify the type and number of elements to
allocate. The elements in the array allocated by new will automatically be initialized to
zero. This example allocates a 12-element array of integers and links them to
month_days.
month_days = new int[12];
After this statement executes, month_days will refer to an array of 12 integers. Further,
all elements in the array will be initialized to zero.
Let's review: Obtaining an array is a two-step process. First, you must declare a variable
of the desired array type. Second, you must allocate the memory that will hold the array,
using new, and assign it to the array variable. Thus, in Java all arrays are dynamically
allocated. If the concept of dynamic allocation is unfamiliar to you, don't worry. It will be
described at length later in this book.
Once you have allocated an array, you can access a specific element in the array by
specifying its index within square brackets. All array indexes start at zero. For example,
this statement assigns the value 28 to the second element of month_days.
month_days[1] = 28;
The next line displays the value stored at index 3.
System.out.println(month_days[3]);
Putting together all the pieces, here is a program that creates an array of the number of
days in each month.
// Demonstrate a one-dimensional array.
class Array {
public static void main(String args[]) {
int month_days[];
month_days = new int[12];
month_days[0] = 31;
month_days[1] = 28;
month_days[2] = 31;
month_days[3] = 30;
month_days[4] = 31;
month_days[5] = 30;
month_days[6] = 31;
month_days[7] = 31;
month_days[8] = 30;
month_days[9] = 31;
month_days[10] = 30;
month_days[11] = 31;
System.out.println("April has " + month_days[3] + " days.");
}
}
When you run this program, it prints the number of days in April. As mentioned, Java
array indexes start with zero, so the number of days in April is month_days[3] or 30.
It is possible to combine the declaration of the array variable with the allocation of the
array itself, as shown here:
int month_days[] = new int[12];
This is the way that you will normally see it done in professionally written Java programs.
Arrays can be initialized when they are declared. The process is much the same as that
used to initialize the simple types. An array initializer is a list of comma-separated
expressions surrounded by curly braces. The commas separate the values of the array
elements. The array will automatically be created large enough to hold the number of
elements you specify in the array initializer. There is no need to use new. For example, to
store the number of days in each month, the following code creates an initialized array of
integers:
// An improved version of the previous program.
class AutoArray {
public static void main(String args[]) {
int month_days[] = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31,
30, 31 };
System.out.println("April has " + month_days[3] + " days.");
}
}
When you run this program, you see the same output as that generated by the previous
version.
Java strictly checks to make sure you do not accidentally try to store or reference values
outside of the range of the array. The Java run-time system will check to be sure that all
array indexes are in the correct range. (In this regard, Java is fundamentally different
from C/C++, which provide no run-time boundary checks.) For example, the run-time
system will check the value of each index into month_days to make sure that it is
between 0 and 11 inclusive. If you try to access elements outside the range of the array
(negative numbers or numbers greater than the length of the array), you will cause a runtime
error.
Here is one more example that uses a one-dimensional array. It finds the average of a
set of numbers.
// Average an array of values.
fclass Average {
public static void main(String args[]) {
double nums[] = {10.1, 11.2, 12.3, 13.4, 14.5};
double result = 0;
int i;
for(i=0; i<5; i++)
result = result + nums[i];
System.out.println("Average is " + result / 5);
}
}
Multidimensional Arrays
In Java, multidimensional arrays are actually arrays of arrays. These, as you might
expect, look and act like regular multidimensional arrays. However, as you will see, there
are a couple of subtle differences. To declare a multidimensional array variable, specify
each additional index using another set of square brackets. For example, the following
declares a two-dimensional array variable called twoD.
int twoD[][] = new int[4][5];
This allocates a 4 by 5 array and assigns it to twoD. Internally this matrix is implemented
as an array of arrays of int. Conceptually, this array will look like the one shown in Figure
The following program numbers each element in the array from left to right, top to bottom,
and then displays these values:
// Demonstrate a two-dimensional array.
class TwoDArray {
public static void main(String args[]) {
int twoD[][]= new int[4][5];
int i, j, k = 0;
for(i=0; i<4; i++)
for(j=0; j<5; j++) {
twoD[i][j] = k;
k++;
}
for(i=0; i<4; i++) {
for(j=0; j<5; j++)
System.out.print(twoD[i][j] + " ");
System.out.println();
}
}
}
This program generates the following output:
0 1 2 3 4
5 6 7 8 9
10 11 12 13 14
15 16 17 18 19
When you allocate memory for a multidimensional array, you need only specify the
memory for the first (leftmost) dimension. You can allocate the remaining dimensions
separately. For example, this following code allocates memory for the first dimension of
twoD when it is declared. It allocates the second dimension manually.
int twoD[][] = new int[4][];
twoD[0] = new int[5];
twoD[1] = new int[5];
twoD[2] = new int[5];
twoD[3] = new int[5];
While there is no advantage to individually allocating the second dimension arrays in this
situation, there may be in others. For example, when you allocate dimensions manually,
you do not need to allocate the same number of elements for each dimension. As stated
earlier, since multidimensional arrays are actually arrays of arrays, the length of each
array is under your control. For example, the following program creates a twodimensional
array in which the sizes of the second dimension are unequal.
// Manually allocate differing size second dimensions.
class TwoDAgain {
public static void main(String args[]) {
int twoD[][] = new int[4][];
twoD[0] = new int[1];
twoD[1] = new int[2];
twoD[2] = new int[3];
twoD[3] = new int[4];
int i, j, k = 0;
for(i=0; i<4; i++)
for(j=0; jtwoD[i][j] = k;
k++;
}
for(i=0; i<4; i++) {
for(j=0; jSystem.out.print(twoD[i][j] + " ");
System.out.println();
}
}
}
This program generates the following output:
0
1 2
3 4 5
6 7 8 9
The array created by this program looks like this:
The use of uneven (or, irregular) multidimensional arrays is not recommended for most
applications, because it runs contrary to what people expect to find when a
multidimensional array is encountered. However, it can be used effectively in some
situations. For example, if you need a very large two-dimensional array that is sparsely
populated (that is, one in which not all of the elements will be used), then an irregular
array might be a perfect solution.
It is possible to initialize multidimensional arrays. To do so, simply enclose each
dimension's initializer within its own set of curly braces. The following program creates a
matrix where each element contains the product of the row and column indexes. Also
notice that you can use expressions as well as literal values inside of array initializers.
// Initialize a two-dimensional array.
class Matrix {
public static void main(String args[]) {
double m[][] = {
{ 0*0, 1*0, 2*0, 3*0 },
{ 0*1, 1*1, 2*1, 3*1 },
{ 0*2, 1*2, 2*2, 3*2 },
{ 0*3, 1*3, 2*3, 3*3 }
};
int i, j;
for(i=0; i<4; i++) {
for(j=0; j<4; j++)
System.out.print(m[i][j] + " ");
System.out.println();
}
}
}
When you run this program, you will get the following output:
0.0 0.0 0.0 0.0
0.0 1.0 2.0 3.0
0.0 2.0 4.0 6.0
0.0 3.0 6.0 9.0
As you can see, each row in the array is initialized as specified in the initialization lists.
Let's look at one more example that uses a multidimensional array. The following
program creates a 3 by 4 by 5, three-dimensional array. It then loads each element with
the product of its indexes. Finally, it displays these products.
// Demonstrate a three-dimensional array.
class threeDMatrix {
public static void main(String args[]) {
int threeD[][][] = new int[3][4][5];
int i, j, k;
for(i=0; i<3; i++)
for(j=0; j<4; j++)
for(k=0; k<5; k++)
threeD[i][j][k] = i * j * k;
for(i=0; i<3; i++) {
for(j=0; j<4; j++) {
for(k=0; k<5; k++)
System.out.print(threeD[i][j][k] + " ");
System.out.println();
}
System.out.println();
}
}
}
This program generates the following output:
0 0 0 0 0
0 0 0 0 0
0 0 0 0 0
0 0 0 0 0
0 0 0 0 0
0 1 2 3 4
0 2 4 6 8
0 3 6 9 12
0 0 0 0 0
0 2 4 6 8
0 4 8 12 16
0 6 12 18 24
Alternative Array Declaration Syntax
There is a second form that may be used to declare an array:
type[ ] var-name;
Here, the square brackets follow the type specifier, and not the name of the array
variable. For example, the following two declarations are equivalent:
int al[] = new int[3];
int[] a2 = new int[3];
The following declarations are also equivalent:
char twod1[][] = new char[3][4];
char[][] twod2 = new char[3][4];
This alternative declaration form is included mostly as a convenience.
A Few Words About Strings
As you may have noticed, in the preceding discussion of data types and arrays there has
been no mention of strings or a string data type. This is not because Java does not
support such a type—it does. It is just that Java's string type, called String, is not a
simple type. Nor is it simply an array of characters (as are strings in C/C++). Rather,
String defines an object, and a full description of it requires an understanding of several
object-related features. As such, it will be covered later in this book, after objects are
described. However, so that you can use simple strings in example programs, the
following brief introduction is in order.
The String type is used to declare string variables. You can also declare arrays of
strings. A quoted string constant can be assigned to a String variable. A variable of type
String can be assigned to another variable of type String. You can use an object of type
String as an argument to println( ). For example, consider the following fragment:
String str = "this is a test";
System.out.println(str);
Here, str is an object of type String. It is assigned the string "this is a test". This string is
displayed by the println( ) statement.
As you will see later, String objects have many special features and attributes that make
them quite powerful and easy to use. However, for the next few chapters, you will be using
them only in their simplest form.
A Note to C/C++ Programmers About Pointers
If you are an experienced C/C++ programmer, then you know that these languages provide
support for pointers. However, no mention of pointers has been made in this chapter. The
reason for this is simple: Java does not support or allow pointers. (Or more properly, Java
does not support pointers that can be accessed and/or modified by the programmer.) Java
cannot allow pointers, because doing so would allow Java applets to breach the firewall
between the Java execution environment and the host computer. (Remember, a pointer
can be given any address in memory—even addresses that might be outside the Java runtime
system.) Since C/C++ make extensive use of pointers, you might be thinking that their
loss is a significant disadvantage to Java. However, this is not true. Java is designed in
such a way that as long as you stay within the confines of the execution environment, you
will never need to use a pointer, nor would there be any benefit in using one. For tips on
converting C/C++ code to Java, including pointers, see Chapter 28.
The operands of the arithmetic operators must be of a numeric type. You cannot use
them on boolean types, but you can use them on char types, since the char type in Java
is, essentially, a subset of int.

No comments: