23.11.2014 Views

Data Structures and Algorithms in Java[1].pdf - Fulvio Frisone

Data Structures and Algorithms in Java[1].pdf - Fulvio Frisone

Data Structures and Algorithms in Java[1].pdf - Fulvio Frisone

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

for the comparison "a[i] > 0.5" will only be performed if the first two<br />

comparisons succeed.<br />

1.5.1 Declar<strong>in</strong>g Arrays<br />

One way to declare <strong>and</strong> <strong>in</strong>itialize an array is as follows:<br />

element_type[] array_name = {<strong>in</strong>it_val_0,<strong>in</strong>it_val_1,…,<strong>in</strong>it_val_N−1};<br />

The element_type can be any <strong>Java</strong> base type or class name, <strong>and</strong> array_name can be<br />

any value <strong>Java</strong> identifier. The <strong>in</strong>itial values must be of the same type as the array.<br />

For example, consider the follow<strong>in</strong>g declaration of an array that is <strong>in</strong>itialized to<br />

conta<strong>in</strong> the first ten prime numbers:<br />

<strong>in</strong>t[] primes = {2, 3, 5, 7, 11, 13, 17, 19, 23, 29};<br />

In addition to creat<strong>in</strong>g an array <strong>and</strong> def<strong>in</strong><strong>in</strong>g all its <strong>in</strong>itial values when we declare it,<br />

we can declare an array variable without <strong>in</strong>itializ<strong>in</strong>g it. The form of this declaration<br />

is as follows:<br />

element_type[] array_name;<br />

An array created <strong>in</strong> this way is <strong>in</strong>itialized with all zeros if the array type is a number<br />

type. Arrays of objects are <strong>in</strong>itialized to all null references. Once we have<br />

declared an array <strong>in</strong> this way, we can create the collection of cells for an array later<br />

us<strong>in</strong>g the follow<strong>in</strong>g syntax:<br />

new element_type[length]<br />

where length is a positive <strong>in</strong>teger denot<strong>in</strong>g the length of the array created. Typically<br />

this expression appears <strong>in</strong> an assignment statement with an array name on the left<br />

h<strong>and</strong> side of the assignment operator. So, for example, the follow<strong>in</strong>g statement<br />

def<strong>in</strong>es an array variable named a, <strong>and</strong> later assigns it an array of 10 cells, each of<br />

type double, which it then <strong>in</strong>itializes:<br />

double[] a;<br />

//… various steps …<br />

a = new double[10];<br />

for (<strong>in</strong>t k=0; k < a.length; k++) {<br />

}<br />

a[k] = 1.0;<br />

62

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!