type[] arrayName; // preferred type arrayName[]; // alternate form
arrayName = new type[size]; // type should match the type of the arrayName variableExamples:
int[] list; // declare an array variable, "list" list = new int[30]; // creates an array of 30 integers char[] name; // declare array variable, "name" name = new char[20]; // creates an array of 20 chars double[] nums; // declare array variable, "nums" nums = new double[x]; // creates an array of x doubles
type[] arrayName = new type[size];Examples:
int[] list = new int[30]; char[] name = new char[20]; double[] nums = new double[x];The array's size is stored in arrayName.length. For example, the size of the "list" array above is:
list.length
int x; int[] list = new int[5]; // create array double[] nums = new double[10]; // create array list[3] = 6; // assign value 6 to array item with index 3 System.out.print(nums[2]); // output array item with index 2 list[x] = list[x+1]; // set values in list array to {1, 3, 5, 7, 9} for (int i = 0; i < list.length; i++) list[i] = i * 2 + 1;Note that this last example, the for-loop, illustrates a good way to set all values in an array. Arrays and for-loops go great together!
type[] arrayName = { initializer list };The initializer list is a comma-separated list of array values. From this, the compiler can figure out the number of elements when creating the array. Examples:
int[] list = {2, 4, 6, 8, 10, 12, 14, 16}; // has size 8 double[] grades = {96.5, 88.4, 90.3, 70.1}; // has size 4 char[] vowels = {'a', 'e', 'i', 'o', 'u'}; // size 5
int[] list1 = new int[5]; int[] list2 = {3, 5, 7, 9, 11};
With variables, we use the assignment statement, so this would be the natural tendency -- but it is wrong!
list1 = list2; // this does NOT copy the array contents
We must copy between arrays element by element. A for loop makes this easy, however:
for (int i = 0; i < list2.length; i++) list1[i] = list2[i];There is also a method called arraycopy in the java.lang.System class. It's format is:
arraycopy(sourceArray, src_pos, targetArray, tar_pos, length);src_pos and tar_pos indicate the starting positions to use in the copy process. length is the number of elements to be copied. Sample call:
// this call is equivalent to the for-loop example above System.arraycopy(list2, 0, list1, 0, list2.length);
int[][] table = new int[5][3]; // a 5 x 3 table of integers short[][] matrix = { {3, 4, 5}, {1, 2, 3}, {0, 5, 9}, {8, 1, -2} }; // a 4 x 3 matrix of short integersFor a 2 dimensional array, we usually think of the first size as rows, and the second as columns, but it really does not matter, as long as you are consistent! We could think of the first array above as a table with 5 rows and 3 columns, for example.
When using a multi-dimensional array, make sure that the indices are always used in the same order:
table[3][1] = 5; // assigns a 5 to "row 3, column 1", in the above interpretation