Create 1D and 2D Arrays
An array is essentially a container object that stores values of the same type. The length of an array is established when the array is created. After an array is created it cannot change length. Below is a diagram showing the parts of an array:
You use the index of the array to locate a specific element within the array. For example, you want to add up the third and the fourth element in the array-- you would refer to them by their index number rather than their actual value. The first element in an array is index 0, the second is index 1, and so on.
Arrays hold objects of the same type. You can create an integer array (int), double array (double), or string array (String). However, you cannot combine two different types of objects within one array.
Example of a correct array: String[] animals = {"cat", "dog", "parrot", "lizard"}; // contains one object type*
Example of an incorrect array: int[] numbers = {1, 2, "three", 4, "five"}; // contains two object types
* double backslash creates a comment in your code. The comments do not alter your code.
There are two ways to create arrays in java. You can declare the array length in one line and then create a new line for each position of the array. The other way is to declare the array and state what is in each position of the array all on one line.
Here is the first way:
Here is the second way:
In addition to one dimensional arrays you can also create two dimensional arrays (also known as a matrix).
Below is an example of the proper syntax for creating a 2D array.
Once you create an array there are ways that you can access its parts. In order to do this you must "call" on a position in the array. You can call on a position in the array in order to print it, use it in an equation, etc. Below are a few examples of how you can access positions of an array. Note that accessing a position of a 2D array is different than a 1D array.
Print an element of a 1D array:
Print an element of a 2D array:

Comments
Post a Comment