Monday, November 21, 2011

Array length

Tip: Once an array object is created, its length never changes. To make an array variable refer to an array of different length, a reference to a different array must be assigned to the variable.

We don't have any method in array to change its length, we can try changing the length of variable by creating two different array instance and printing its length.
class ArrayLength {

 public static void main(String[] args) {
  int [] a = {1, 2, 3};
  System.out.println("Length : " + a.length);
  
  a = new int [2];
  System.out.println("Length : " + a.length);
 }
} 
If we compile and run this code, output will be:

Length : 3
Length : 2
Next exercise we will try to increase length of array by assigning at an index more than the array was initialized with.
 ArrayLength {

 public static void main(String[] args) {
  int [] a = {1, 2, 3};
  System.out.println("Length : " + a.length);

  a [3] = 4;
  System.out.println("Length : " + a.length);
 }
}
When above code is run, it will throw java.lang.ArrayIndexOutOfBoundsException
Length : 3
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 3
 at com.quiz.questions.ArrayLength.main(TestArray.java:18)
Very simple fact, but sometimes even the experienced programmers miss this.

Available in Android Market

No comments:

Post a Comment