Wednesday 7 September 2011

Java: Containers (Arrays)

    Today, we learn about arrays! This is a very basic container type, directly integrated into Java. They hold collections of values (elements of the array), all of which must be the same type (That is, any type, as long as its consistent).
    Arrays are contiguous sequences of variables, where each variable contains a single value. The array has its overall name as defined by the programmer who created it, with each element being accessed through the array name, followed by the index of the desired element in square brackets. Since programmers count from 0, an array of 10 integers would be indexed from 0-9.

int[] exampleArray = new int[10];

    The above code creates an integer array ( int[] ), names it, then specifies its length ( int[10] ), 10.  String[] and whatever other class you want can be used instead of int, but int is easier to type, so that'll remain my examples.  

    Now to fill this array variable with actual values!

for ( int i = 0 ; int < exampleArray.length ; i++ ) {
    exampleArray[ i ] = i + 1;
}

    This should fill our array with the numbers 1 - 10, if you have trouble understanding the code, leave a comment below. You can now access whichever element you want by typing out exampleArray followed by whichever index you want. Be warned, you can't just print out the array using:

System.out.println(exampleArray);

...since this will return the pointer to the array, not the elements within. Pointers come later, as does more posting. Comment, follow, share, what have you, and see you tomorrow, hopefully!

1 comment:

  1. i always wanted to learn how to program. Your blog should be very interesting for me.

    ReplyDelete