Programming Tutorials

Arrays in Java

By: aathishankaran in Java Tutorials on 2007-03-16  

An important point can be made about arrays: they are implemented as objects. Because of this, there is a special array attribute that you will want to take advantage of. Specifically, the size of an array that is, the number of elements that an array can hold is found in its length instance variable. All arrays have this variable, and it will always hold the size of the array. Here is a program that demonstrates this property:

class Length {
 public static void main (String args[]) {
  int a1[] = new int[10];
  int a2[] = {3, 5, 7, 1, 8, 99, 44, -10};
  int a3[] = {4, 3, 2, 1};

  System.out.println("length of a1 is " + a1.length);
  System.out.println("length of a1 is " + a1.length);
  System.out.println("length of a1 is " + a1.length);
 }
}

This program displays the following output:

length of a1 is 10
length of a1 is 8
length of a1 is 4

As you can see, the size of each array is displayed. Keep in mind that the value of length has nothing to do with the number of elements that are actually in use. It only reflects the number of elements that the array is designed to hold.

You can put the length member to good use in many situations. For example, here is an improved version of the stack class. As you might recall, the earlier versions of this class always created a ten-element stack. The following version lets you create stacks of any size. The value of stck.length is used to prevent the stack from overflowing:

class Stack {

 private int stck[] {
 private int tos;

 Stack(int size) {
	  stck = new int[size];
	  tos = -1;
}

void push(int item) {
 if(tos==stck.ength-1)
	  System.out.println("Stack is full.");
 else
	  stck[++tos] = item;
}
 
int pop() {
 if (tos < 0) {
	  System.out.println("Stack underflow.");
	  return 0;
 }
 else
 return stck[tos--];
 }
}
 
class TestStack2 {

 public static void main(String args[]) {
  Stack mystack1 = new Stack(5);
  Stack mystack2 = new Stack(8);        

  for(int i=0; i<5; i++) mystack1.push(i);
  for(int i=0; i<8; i++) mystack2.push(i);

  System.out.println("Stack in mystack1:");
  for(int i=0; i<5; i++)
		System.out.println(mystack1.pop());
  System.out.println("Stack in mystack2:");
  for(int i=0; i<8; i++)
		System.out.println(mystack2.pop());
}
}

Notice that the program creates two stacks: one five elements deep and the other eight elements deep. As you can see, the fact that arrays maintain their own length information makes it easy to create stacks of any size.






Add Comment

* Required information
1000

Comments

No comments yet. Be the first!

Most Viewed Articles (in Java )

Latest Articles (in Java)