arrays
Methods of declaring an array
//How to declare an array
//Method 1
int[] anArray;
anArray = new int[10];
//Method 2
int anArray[];
anArray[] = new int[10];
//Method 3
int[] anArray = new int[10];
//Method 4
int anArray[] = new int[10];
General tips on arrays
// Declares an array with 4 elements of type String
String[] dogs = new String[4];
// This populates our array with data, notice how the array starts at 0 and ends at 3
dogs[0] = "Rex";
dogs[1] = "Sparky";
dogs[2] = "Rover";
dogs[3] = "Lassie";
// If we try to access an element that doesnt exist in our array we get an ArrayIndexOutOfBoundsException
System.out.println("The dogs name is " + dogs[4])
A simple example of an array of strings
public class ArrayExample
{
public static void main(String args[])
{
// Arrays are used to store values of the same type.
// This array is an array of String type.
String[] month;
month = new String[12];
// Arrays start at an index of 0, so if there is 12 elements the first element will be 0 and the last element will be 11
month[0] = "January";
month[1] = "February";
month[2] = "March";
month[3] = "April";
month[4] = "May";
month[5] = "June";
month[6] = "July";
month[7] = "August";
month[8] = "September";
month[9] = "October";
month[10] = "November";
month[11] = "December";
//This will print out February and not january as the index starts at 0.
System.out.println("The month is " + month[1]);
}
}
A simple example of an array of integers
public class IntArrayExample
{
public static void main(String args[])
{
// Creating an array of integers with 10 elements
int[] numbers;
numbers = new int[10];
// If u tried to insert a string or double into this array you would get an error as it will only accept integers.
numbers[0] = 10;
numbers[1] = 20;
numbers[2] = 30;
numbers[3] = 40;
numbers[4] = 50;
numbers[5] = 60;
numbers[6] = 70;
numbers[7] = 80;
numbers[8] = 90;
numbers[9] = 100;
System.out.println("Your number is " + numbers[4]);
}
}
page revision: 6, last edited: 22 Feb 2011 10:27