Java & J2EE Page 2 - Primitive Data Types and Basic Language Rules for Java |
While they won't let you see through walls like their cousin, the X-ray, Arrays act as a holding cell for multiple values of the same type. It's like taking a group of variables and some glue and sticking them all together. When you create an array, you must determine its length. This length determines the number of placeholders within the array; this number does not change once the array is created. A good way to think of it is like an egg carton. When you go to the store you can buy six eggs or twelve eggs (or if you are an eggomaniac, you can opt for the deluxe 24 pack, but come on, let's not get clucking crazy). Each little crate within that pack was at one point empty. Then they placed it on an assembly line and let the chickens do their thing. Soon, an egg was placed into each holder. Since the carton was only created to hold 12 eggs, you can't put anymore into it. And since it is an egg carton, you can't place anything but eggs within it. Anything you put into an array is referred to as an element. And every element has an index number for you to to refer to it.
In the above display, you will notice there are five boxes, meaning the array has a length of five. Each box of the array has an index number, starting with the number zero and working its way to the number four. Also, you will notice that Index 0 has something inside it, or an element. The other indexes are empty and are waiting to be assigned a value. The way we create and assign a value is shown below. class ArrayXray { public static void main(String[] args) { int[] YourArray; // declaring an array of integers YourArray = new int[5]; // allocates memory for 5 integers
YourArray[0] = 100; // initializes or sets the first element YourArray[1] = 200; // initializes second element YourArray[2] = 300; // so forth YourArray[3] = 400; YourArray[4] = 500; In the above example, you have created a new array named "Your Array." We made the array an integer (int) data type and assigned it five elements. Then we gave each of those elements a value. Once you have created your array, you can not change it later without recreating the original array. We also initialized the array using the word new. Without doing so we would have been yelled at by the compiler and received an F on our report card, not to mention an error message. You can also declare an array in the following manner: int[] YourArray = {100, 200, 300, 400, 500}; You'll note in the above sample that the length of the array is determined by the number of values between the "{" and "}" brackets.
blog comments powered by Disqus |
|
|
|
|
|
|
|