Welcome to Anythingweb.org
You are not Logged in! Log in to check your messages.
Anythingweb.org
Resources for Webmasters.
Today's:
Popular Articles and Posts:
Popular Articles and Posts:
An Introduction to Java Arrays
Submitted by: web_guy
Hits:263
There are many times when you have a sequential list that you want to store and access. An easy and probably the most popular
way to store this lists, in Java, is with arrays. An array is a list of variables that share the name and are ordered
sequentially from 0 to one less the number of variables.
Below is a visual look at a Java array.
| 0 | 1 | 2 | 3 | 4 |
| value 0 | value 1 | value 2 | value 3 | value 4 |
To create a Java array, you must first declare it. Then allocate it ,and finally you must initialize it.
Java arrays must first be declared. By declaring an array, you are simply saying what the array is. Like other variables in Java, arrays must be assigned a type. For example, Java arrays can be int, String, double, or byte. An array can just store the type you assign it. An array assigned to a String type can not store a int type.
The following examples are how you can declare a Java array.
int[ ] employeeNumbers;
String[ ] employeeNames;
Now that you have the area type, you must actually create the array. Here you will actually create the array and specify its size so there is RAM set aside. The numbers inside the brackets are called dimensions. The dimensions tell the array how many elements you can store.
The following example so you how to create the array.
employeeNumbers = new int[5];
employeeNames = new String[15];
Next we are going to set values to the each element in the array. This is called initializing the array.
employeeNumbers[0] = 1;
employeeNumbers[1] = 2;
employeeNumbers[2] = 3;
.........and so on up to 4.
I can only go up to 4 elements because you must include 0 in your count.
employeeNames[0] = "Bob";
employeeNames[1] = "Jim";
employeeNames[2] = "Frank";
.........and so on up to 14.
I can only go up to 14 because you must include 0 in your count.
It takes a total of three steps to declare, allocate, and initialize a Java array. In the following examples, you will see that you can combine a few of these steps to make it simpler.
Here we will declare and allocate in the same step.
int employeeNumbers[] = new int[5];
String[] employeeNames[] = new String[15];
Here we will declare, allocate, and initialize in the same step.
int employeeNumbers[] = {1,2,3,4,5}; String employeeNames[] = {"Bob", "Frank", "Jim", .... and so on until you have your full list.};
There are three steps to creating arrays. You must declare allocate, and then initialize the array. You can do each one as a separate step, or you can combine steps to speed up coding.
SEO