Win a copy of Functional Reactive Programming this week in the Other Languages forum!

# array?

Ayesha Khan
Greenhorn
Posts: 1
what is meant by an array?

seema mani
Ranch Hand
Posts: 49
An array is a collection of elements which belong to the same datatype.They will be stored in adjacent memory locations and can be accessed by specifying the array name & index .

Dan Lund
Greenhorn
Posts: 26
an array is kind of a set of variables stored in another variable....

tyler jones
Ranch Hand
Posts: 101
Here's an example of an array...

//create our array

//assign the values to our array

Okay, now for the explanation. First off, we declare a variable called names of the datatype String. With arrays, I can have multiple variables that all share the same name, but are referenced through an index number. When I declare my String names variable, it's followed by [] indicating that I'm creating an array. After the = sign, I assign the number of positions in my array. In this case my array will have 3 positions. One thing to remember is that arrays are always 0 based. This is something many beginners stumble over, but after a couple of times through some array practices, it becomes habit to think of arrays this way.
So, now that we have our array "names" created with 3 empty slots to fill, we fill those slots. Like I said, arrays are 0 based which is why the first one starts with names[0]. After we've filled up all 3 positions of our array, we can run through each position in our array with a for loop. The for loop starts at 0 because of the array being 0 based. The ending point of our loop is the length of the array minus 1. The reason for this is because the length of our array is 3. However if we run our loop from 0 to 3, it will actually run 4 times and thereby run outside the upper bound of the loop causing an error. So, when you use the .length() method to determine the ending position of your loop, you want to actually use the length of the array minus one as your ending point. Next we tell the loop to increment by one each time through. Therefore, when we run through the array, i will hold the value of 0 the first time, 1 the 2nd time, and 2 the third time. Because of this, our print out to the screen is ...
Mary
David
Greg
The last bit of code shows how easily you can change the value of any element of your array. You simply reference the element by it's index position in your array and assign the new value to it. Arrays can seem intimidating to the newbie, but they are not really too difficult to grasp and use, and they are extremely powerful. Especially when you start using multi dimensional arrays. But that's a whole nother subject (and long post . I hope this has helped.

Bosun Bello
Ranch Hand
Posts: 1511
Good explanation Tyler. Ayesha, you can also check out the java tutorial at sun's site. Actually any good java textbook (I recommend Beggining Java 2 by Ivor Horton) will give you good explanation and examples.

Bosun