Arrays


While Java and C both start array indices from zero, there is a fundamental difference in the way the two languages treat arrays. With C, an array of a given data type is treated as a sequence of members of that type stored in contiguous locations in memory. The declaration syntax is the data type, the array name , and the size of the array enclosed in brackets.

 int data[5]; 

The members of a C array can be accessed using the array name and index or with a pointer to the array. C arrays can be given a fixed size when they are declared or you can create a dynamically allocated array using pointers and the malloc() function.

In Java, arrays are reference types just like class instances. Creating a Java array is a two-step process. You first declare an array variable by specifying its type and name followed by a pair of brackets ”

 int data[]; 

Declaring an array variable does not allocate any memory for it. The second step in the array creation process is to allocate memory for the array variable using the new keyword followed by the type and size of the array.

 data = new int[5]; 

The two steps can be combined to a single line

 int data[] = new int[5]; 

Elements of a C array can be accessed either through the array index or by using a pointer to the array. Because Java does not support pointers, Java array elements are accessed only through indexes. Both C and Java use a pair of brackets around the index of the element to be accessed. For example, to assign the value 45 to the third element of an array named data you would type ”

 data[2] = 45; 

When looking at the above syntax, keep in mind that Java array indices start at 0. The first element of the data array would be data[0] .



Technical Java. Applications for Science and Engineering
Technical Java: Applications for Science and Engineering
ISBN: 0131018159
EAN: 2147483647
Year: 2003
Pages: 281
Authors: Grant Palmer

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net