Java Array

Java Array Print E-mail
Contributed by mark   
Thursday, 13 July 2006

Java Array overview

An array is a special kind of object that holds zero or more primitive values or references. These values are held in the elements of the array, which are unnamed variables referred to by their position or index. The type of an array is characterized by its element type , and all elements of the array must be of that type.

Array elements are numbered starting with zero, and valid indexes range from zero to the number of elements minus one. The array element with index 1, for example, is the second element in the array. The number of elements in an array is its length. The length of an array is specified when the array is created, and it never changes.

The element type of an array may be any valid Java type, including array types. This means that Java supports arrays of arrays, which provide a kind of multidimensional array capability. Java does not support the matrix-style multidimensional arrays found in some languages.

Java Array Types

Array types are reference types, just as classes are. Instances of arrays are objects, just as the instances of a class are.Unlike classes, array types do not have to be defined. Simply place square brackets after the element type. Array types are not classes, but array instances are objects. This means that arrays inherit the methods of java.lang.Object. For example, the following code declares two variables of array type:

byte[] arrayOfBytes;           // byte[] is an array type: array of byte
String[] strs;               // String[] is an array of String objects

Creating and Initializing Java Arrays

 Using the new keyword to create an array value in Java,You must specify a length whenever you create an array.for example

byte[] buffer = new byte[1024];  // Create a new array to hold 1024 bytes
String[] strs = new String[10]; // Create an array of 10 references to strings

Array bounds

The first element of an array str is str[0] , the second element is str[1] and the last is str[str.length-1]. If an array index is too small or too large, Java throws an ArrayIndexOutOfBoundsException immediately.

Copying java arrays

All java array types implement the Cloneable interface, and any array can be copied by invoking its clone( ) method.

int[] age = { 21, 31, 16 };
int[] copyage = (int[]) age.clone(  );

 The clone( ) method makes a shallow copy. If the element type of the array is a reference type, only the references are copied, not the referenced objects themselves. Because the copy is shallow, any array can be cloned, even if the element type is not itself Cloneable.

If you want to copy elements from one existing array to another existing array. just use System.arraycopy( ) method ,for example

    // Shift all elements right by one
    System.arraycopy(array, 0, array, 1, array.length-1);
    // Shift all elements left by one
    System.arraycopy(array, 1, array, 0, array.length-1);

Expanding a java Array

The length of an array cannot be changed. So the best way is to expanding an array is to create a larger one of the same type and copy the contents from the old array. 

    Object newArray = Array.newInstance(array.getClass().getComponentType(), Array.getLength(array)*2);
    System.arraycopy(array, 0, newArray, 0, Array.getLength(array));

Finding an Element in a Sorted Array

    // Create an array with an ordered list of strings
    String[] sortedArray = new String[]{"IBM", "MS", "SUN"};
    // Search for the word "MS",index will be 1
    int index = Arrays.binarySearch(sortedArray, "MS");  
    // Search for a non-existent element
    index = Arrays.binarySearch(sortedArray, "APPLE");  
A negative return value indicates that the element is not in the list

Questions about java array

1. public class ArrayTest {
2. public static void main(String[] args) {
3. float fl[], f2[];
4. fl = new float[10];
5. f2 = f1;

6. System.out.println(“f2[0]= “ + f2[0]);
7. }
8. }
What is the result?

A.  It prints f2[0] = 0.0. B.  It prints f2[0] = NaN.
C.  An error at line 5 causes compile to fail. D.  An error at line 6 causes compile to fail.
E.   An error at line 6 causes an expectation at runtime.

12. float f[][][] = new float[3][][];
13. float f0 = 1.0f;
14. float[][] farray = new float[1][1];
What is valid?
A.  f[0] = f0;
B.  f[0] = farray;
C.  f[0] = farray[0];
D.  f[0] = farray[0][0];

Last Updated ( Thursday, 13 July 2006 )

  home              contact us


©2006-2014   All rights reserved     powered by Mambo Designed by Siteground