ARRAYS - I

Arrays

Java arrays are similar to ideas in mathematics

An array can store many similar values in memory. Each value can be accessed by specifying a subscript or index. "Array" in Java means approximately the same thing as array, matrix, or vector does in math.

Unlike math, you must declare the array and allocate a fixed amount of memory for it.

 
Declaring an array

An array variable is like other variables -- you must declare it, which means you must declare the type of elements that are in an array. All elements must be the same type. Write the element type name, then "[]", then the name of the array variable. The declaration allocates only enough space for a reference to an array (typically 4 bytes), but doesn't create the actual array object.

String[]  args;   // args is an array of Strings

int[]     scores; // scores is an array of ints

JButton[] bs;     // bs is an array of JButtons

No size in declaration. Unlike some languages, never put the size of the array in the declaration because an array declaration specifies only the element type and the variable name.

Allocate an array object with new

Create an array using new. This example creates an array of 100 int elements, from a[0] to a[99].

int[] a;           // Declare a to be an array of ints

a = new int[100];  // Allocate an array of 100 ints

These are often combined in one line.

int[] a = new int[100];  // Declare and allocate.

Subscripts

Subscripts are enclosed in square brackets []. xi in mathematics is x[i] in Java, and is pronounced "x-sub-i".

Subscript ranges always start at zero because Java came largely from C++, which had a good reason for using zero (pointer arithmetic on arrays). It isn't the way that humans normally count; you'll just have to live with it.

Java always checks subscript legality to be sure the subscript is >= 0, and less than the number of elements in the array. If the subscript is outside this range, Java throws ArrayIndexOutOfBoundsException. This is far superior to the behavior of C and C++, which allow out of range references. Consequently, Java programs are far less susceptible to bugs and security flaws than C/C++ programs.

Length of an array

Each array has a constant (final) instance variable that has its length. You can find out how many elements an array can hold by writing the array name followed by .length. In the previous example, a.length would be 100. Remember that this is the number of elements in the array, one more than the maximum subscript.

Java idiom for looping over an array

The most common use of .length is in a for loop test condition. For example, the variable i will go over the entire range of subscripts of the array a.

for (int i=0; i < a.length; i++) {

    . . .

}

If you only need to reference the value of each of the elements, you can use the somewhat simpler Java 5 for loop, which keeps track of the index and assigns successive values to a variable (v in this example).

for (int v : a) {

    . . .

}

Example Version 1 -- Adding all elements of an array

These statements create an array and put 1000 random values in it. The second loop adds all 1000 elements. It would have been better to add them in the first loop, but writing it this way allows two examples of loops.

int[] a;           // Declare an array of ints

a = new int[1000]; // Create an array of 1000 ints, a[0]...a[999] 

//... Assign random values to each element.

for (int i=0; i<a.length(); i++) {

    a[i] = (int)(Math.random() * 100000);  // Random number 0-99999

} 

//... Add all values in the array.

int sum = 0;           // Start the total sum at 0.

for (int i=0; i<a.length; i++) {

    sum = sum + a[i];  // Add the next element to the total

}

Example Version 2 -- Adding all elements of an array in Java 5

This is the the same as above, but uses the Java 5 "for each" loop to do the sum, which frees you from using an index if you simply need to get all successive values. This kind of loop only gets the values, so it couldn't have been used to set the values in the first loop above.

. . .

int sum = 0;        // Start the total sum at 0.

for (int v : a) {

    sum = sum + v;  // Add the next element to the total

}

Initial array element values -- zero/null/false

When an array is allocated (with new), all elements are set to an initial value. The initial value is 0 if the element type is numeric (int, float, ...), false for boolean, and null for all object types.

Array Initialization

When you declare an array, you can can also allocate a preinitialized array object in the same statement. In this case, do not give the array size because Java counts the number of values to determine the size. For example,

// Java 1.0 style -- shorter, but can be used ONLY IN DECLARATIONS

String[] days = {"Su", "Mo", "Tu", "We", "Th", "Fr", "Sa"};

Array variables are references to arrays

When you declare an array variable, Java reserves only enough memory for a reference (Java's name for an address or pointer) to an array object. References typically require only 4 bytes. When an array object is created with new, a reference is returned, and that reference can then be assigned to a variable. When you assign one array variable to another, only the reference is copied. For example,

int[] a = new int[] {100, 99, 98};

int[] b;

// "a" points to an array, and "b" doesn't point to anything

b = a;      // Now b referes to the SAME array as "a"

b[1] = 0;   // Also changes a[1] because a and b refer to the same array.

// Both a and b refer to same array with value {100, 0, 98}

1 comments:

Unknown said...

nice topic. Its help people to learn array in java

thanks,
kausik
http://javacracker.com

Post a Comment