We all recognize variables as places to store data in our programs/applications, but this can become an arduous task, and in many cases the variables are of the same type. But what can we do about it you’re thinking! Well we can use Arrays. Generally speaking an array is a group of similar variable types. Let’s take an example, I have 5 dogs, and I want to write a program to keep track of them. Now since I am lazy, I am not going to give them all a separate variable, but instead use an array; which looks like this: -
String[] myDogs;
Or I could even write: -
String myDogs[];
Flexible eh? The square brackets denote an array, and the string defines their type, and myDogs is the variable name. The above example creates the array, but we can’t actually store any information in there, because we haven’t told the computer to do so! So let’s do it: -
String[] myDogs = { “Aton”, “barnseyboy”, “shn”, “gabbana”, “Rob”};
Not so hard eh? Aton is a good dog who always fetches me the paper, barnseyboy is a poodle; shn and Rob are very lazy; and gabbana spends his time chasing all the lady dogs around the neighborhood.
So we’ve created our array, but how do we access it? I had a feeling you would ask that so let’s say we want to sort the array alphabetically, and print it them out. I would use the following code: -
Int j = 0;
For (j < myDogs.length; j++)
Arrays.sort(myDogs);
System.out.println(“Dog number” + j + “is” + myDogs[j - 1]);
Remember, while using this code; because we are using the .length and .sort methods to import all of the java utils. So to do this just put import java.util.*; at the top of the class.
Not too hard? If you have any questions just pop over to the forums, I’m sure someone will be able to help.
This article was originally written by sliptop |