Kenya Array Types

Arrays are special cases of the Class Types.

An array allows you to store multiple objects of the same type in an indexable, fixed size list.

To declare an array, place square bracket pairs "[]" after the type of the variable you wish to declare, for example:

	void main(){
		int[] x; 		// this declares an array of integers
		String[][] y;	// this declares an array of arrays of String.
	}

with an array declared, it can then be assigned to either null, another array of the same type, or to a new array of a given size. When you assign an array to a new array of a given size, the value of each element of the array is the default for that type ( as described above - the default value for an array is null). If you are declaring an array variable, you can also initialise it with known values;

Example 2.3. Array Initialisation

	void main(){
	
		int[] x = null; 				
			// initialise the array to null.
			
			
		String[] y = new String[10];	
			/* initialise the array with 10 
			String objects each with the
			value null. */
		
		
		boolean[][] b = new boolean[3][3];	
			/* initialise the array with
			   3 arrays each containing 3
			   booleans starting with the 
			   default value of false. */
		
											   
		String[] initStrings = { "Happy", "Flowers" };
			/* initialise the array with two
			   elements, with the values "Happy"
			   and "Flowers" */
		
										   
		int[][] initInts = { { 0, 1 } , { 0, 1 } };
			/* initialise the array with two
			   arrays that both have 0 as the
			   first element, and 1 as the second
			*/
	}

To be able to interrogate an array to get or set the values of what it containts, you index the array with a mathematical expression.

Remember, an array has a fixed length once it has been declared, and you cannot assign or read outside of that length. Also, array indexes start at 0, i.e. an array of length 10 has indexes 0,1,2,3,4,5 ... 9, but index 10 is out of range. To know how long an array is, you can interrogate it for its length; as shown below:

Example 2.4. Array Indexing and Length Interrogation

	void main(){
	
		int[] x = new int[5];
		// x.length returns the length of the array as an int
		
		for( int i = 0 ; i < x.length ; i++ ){
			x[i] = i * i;
		}
	
		println("Squares");
		for( int i = 0 ; i < x.length ; i++ ){
			println( "The number: " + i + " squared is: " + x[i] );
		}
		
		
		println("Powers");
		double[][] powers = new double[10][3];
		for( int i = 0 ; i < powers.length ; i++ ){
			for(int j = 0 ; j < powers[i].length ; j++ ){
				powers[i][j] = pow( i, j );			
			}
		}

		double[][] powers = new double[10][3];
		for( int i = 0 ; i < powers.length ; i++ ){
			for(int j = 0 ; j < powers[i].length ; j++ ){
				powers[i][j] = pow( i, j );			
			}
		}
		
	}