dataType [] arrayName; or dataType arrayName[]; boolean [] status; int [] numPoints; double [] xPos;When you simply declare an array you have not created any space in memory for the contents of the array.
dataType [] arrayName = new dataType [ arraySize ]; char [] alphabet = new char [26];The size of an array cannot be changed after it is created. array.length gives the size of an array. The array variable points to the first element of the array. The elements of the array so far are undefined.
Another way of creating the the array is to specify all the elements of the array:
short [] numList = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
alphabet [2] = 'c';arrayName[i] will return the array element at position i provided i is in the range 0 <= i < array.length.
public static int sumArray ( int[] anArray ) { int sum = 0; for ( int i = 0; i < anArray.length; i++ ) sum += anArray[i]; return sum; }
public static int[] copyArray ( int[] anArray ) { int[] dupArray = new int [anArray.length]; for ( int i = 0; i < anArray.length; i++ ) dupArray[i] = anArray[i]; return dupArray; }
// returns a random number between 1 and 100 // except those numbers in the parameter list public static int getRandom (int... numbers) { boolean found = true; int rand = 0; while (found) { found = false; rand = (int)(100 * Math.random()) + 1; for (int elt: numbers) { if (elt == rand) { found = true; break; } } } return rand; }
final int ROWS = 3; final int COLUMNS = 2; int[][] a = new int [ROWS][COLUMNS]; This array has three rows and two columns a[0][0] a[0][1] a[1][0] a[1][1] a[2][0] a[2][1] To assign a value to any one element a[1][0] = 3; Another way of declaring and assigning values to a two dimensional array is int[][] b = { {9, 8, 7}, {6, 5, 4}}; This is equivalent to b[0][0] = 9 b[0][1] = 8 b[0][2] = 7 b[1][0] = 6 b[1][1] = 5 b[1][2] = 4 To sum over the elements of an array, sum over the columns first and then the rows. int sum = 0; for ( int i = 0; i < ROWS; i++ ) for ( int j = 0; j < COLUMNS; j++ ) sum += a[i][j];