JAVA Arrays

Arrays are containers of values with a single data type like integer (int). Think of an array like this.
java array sample illustration
 To declare an array in JAVA for example using int as the data type;
int[] ages;
or
int ages[];

The open and close square brackets indicates the size of the array. e.g. [10];

To initialize an array in JAVA:
int[] ages = new int[array_length];
int[] ages = new int[10]; //this will create 10 containers of a data type int, because the first index is 0. So this will be 0 - 9 that is a length of 10. In simple terms, the array ages can contain 10 values.
Instead of creating int ages1, int ages2, int ages3,...int ages10; it is best to create an array.

Examples of declaring and initializing an array:

For String;
    String[ ] aStrings = {"January", "February", "March", "April" };
For Boolean:
    boolean[ ] aBools = {true, true, false, false}; (this is wrong!)
    boolean[ ] aBools = new boolean[ ] {true, true, false, false}; (this is correct for setting up a boolean) array. You should add the new keyword.

To Retrieve a value from an Array:
    System.out.println( aStrings[2] ); (this will display "March")

You can also store values into an Array:
    int[] ages = new int[5];
    int[0]=3;
    int[1]=5;
    int[2]=10;
    int[3]=12;
    int[4]=20;

Here is an example Array Project: http://sdrv.ms/TkojVU

Next: String Methods

No comments:

Post a Comment