Showing posts with label for-loop. Show all posts
Showing posts with label for-loop. Show all posts

Monday, May 7, 2012

Java Arrays


Whilst a variable can hold a single data item of a specified type, an array can hold a number of data items of a specified type.

The following example shows an array of 7 strings. The array stores the names of the days of the week. Once this collection is stored, we can access each string in the array by it's index.



Syntax:
Type[] identifier = new Type[length];

Example:
String[] names = new String[10];

Arrays need to be declared as a certain length - for instance, the example above will hold 10 Strings.

Each item in the array occupies an index. Indexes begin at 0 (zero) in an array.



Example: Manually populate an array:

int[] numberList = new int[3]
numberList[0] = 455;
numberList[1] = 22;
numberList[2] = 13;

 Example: Access a particular index of the array:

int selectedIndex = numberList[2];

The above statement will get the element at index [2] and assign it to the variable called selectedIndex. As such, selectedIndex now has a value of 13.

Remember, the array index starts at 0, so in the above example we can say that the 2nd element of the array is at index 1.

Example: Use a for loop to iterate the array and display each index:

Arrays are often used in conjunction with a for-loop. We use the loop counter to access each element in the array.

Arrays have a Length property which will return the number of elements in the array.

for (int x = 0; x < numberList.length; x ++) {
       System.out.println(numberList[x]);
}

The loop is primed in the following way:

  • The loop counter begins at 0 (the same value as the first element of our array)
  • The loop will continue while the loop counter is less than the length of the array
  • The loop counter will be incremented on each pass of the loop

The body of the loop then uses the loop counter to access the current element of the array.

In cases where you need a collection to grow as needed, other collection types such as the ArrayList may be used.

Also see:
"Arrays (The Java™ Tutorials > Learning the Java Language > Language Basics)" ( http://bit.ly/K4Arb2 )