Loading

Java Tutorial Hub

Training & Tutorials for Java Beginners

Java Tutorial 11 - Arrays

 

An array is a very common type of data structure where in all elements must be of the same data type.

 

Once defined , the size of an array is fixed and cannot increase to accommodate more elements.

 

The first element of an array starts with zero.



 

In simple words it’s a programming construct which helps replacing this

 
    x0=0;
    x1=1;
    x2=2;
    x3=3;
    x4=4;
    x5=5;
 
with this …
 
   x[0]=0;
   x[1]=1;
   x[2]=2;
   x[3]=3;
   x[4]=4;
   x[5]=5;
 
how this helps is that the index (the number in the bracket[]) can be referenced by a 
variable for easy looping.
 
   for(count=0; count<5; count++) { 
     System.out.println(x[count]);  
   }
 
Using and array in your program is a 3 step process -
1) Declaring your Array
2) Constructing your Array
3) Initializing your Array

Syntax for Declaring Array Variables is

       <elementType>[] <arrayName>;

                         or

       <elementType> <arrayName>[];

 

Example:

    int intArray[];  // Defines that intArray is an ARRAY variable of which will store integer values

    int []intArray;

 

Constructing an Array

<arrayName> = new <elementType>[<noOfElements>];

Example:

   intArray = new int[10]; // Defines that intArray will store 10 integer values

 

Declaration and Construction combined

   int intArray[] = new int[10];

 

Initializing an Array

   intArray[0]=1; // Assigns an integer value 1 to the first element 0 of the array

   intArray[1]=2; // Assigns an integer value 2 to the second element 1 of the array

 

Declaring and Initializing an Array

   <elementType>[] <arayName> = {<arrayInitializerCode>};

Example:

   int intArray[] = {1, 2, 3, 4}; // Initilializes an integer array of length 4 where the first element is 1 , second element is 2 and so on.

 

Assignment: First Array Program

Step 1) Copy the following code into a editor

 

class ArrayDemo{
     public static void main(String args[]){
        int array[] = new int[7];
        for (int count=0;count<7;count++){
           array[count]=count+1;
       }
       for (int count=0;count<7;count++){
           System.out.println("array["+count+"] = "+array[count]);
       }
      //System.out.println("Length of Array  =  "+array.length);  
      // array[8] =10; 
      }
}

Step 2) Save , Compile & Run the code. Observe the Output

 

Step 3)If x is a reference to an array, x.length will give you the length of the array.

Uncomment line #10 . Save , Compile & Run the code.Observe the Output

 

Step 4)Unlike C, Java checks the boundary of an array while accessing an element in it. Java will not allow the programmer to exceed its boundary.

Uncomment line #11 . Save , Compile & Run the code.Observe the Output

 

Step 5) ArrayIndexOutOfBoundsException is thrown. In case of C , the same code would have shown some garbage value.

arrays are passed by reference


Arrays are passed to functions by reference, or as a pointer to the original. This means anything you do to the Array inside the function affects the original.

 

Assignment: To understand Array are passed by reference

Step 1) Copy the following code into a editor

class ArrayDemo {
 
   public static void passByReference(String a[]);
     a[0] = "Changed";
   }
 
   public static void main(String args[]){
      String []b={"Apple","Mango","Orange"};
      System.out.println("Before Function Call    "+b[0]);
      ArrayDemo.passByReference(b);
      System.out.println("After Function Call    "+b[0]);
   }
}
   

Step 2) Save , Compile & Run the code. Observe the Output

 

multidimensional arrays

 

Multidimensional arrays, are arrays of arrays.

 

To declare a multidimensional array variable, specify each additional index using another set of square brackets.

Ex: int twoD[ ][ ] = new int[4][5] ;

 

When you allocate memory for a multidimensional array, you need only specify the memory for the first (leftmost) dimension.

You can allocate the remaining dimensions separately.

 

In Java the length of each array in a multidimensional array is under your control.

Ex:

int twoD[][] = new int[4][];

twoD[0] = new int[5];

twoD[1] = new int[6];

twoD[2] = new int[7];

twoD[3] = new int[8];

       

 

array of Objects

 

It is possible to declare array of reference variables.

Syntax:

Class <array_name> = new Class[array_length]

 

Assignment: To create Array Of Objects

Step 1) Copy the following code into a editor

class Account{
  int a;
  int b;
 public void setData(int c,int d){
   a=c;
   b=d;
 }
 public void showData(){
   System.out.println("Value of a ="+a);
   System.out.println("Value of b ="+b);
 }
}

class ObjectArray{
   public static void main(String args[]){
     Account obj[] = new Account[2] ;
     //obj[0] = new Account();
     //obj[1] = new Account();
    obj[0].setData(1,2);
    obj[1].setData(3,4);
    System.out.println("For Array Element 0");
    obj[0].showData();
    System.out.println("For Array Element 1");
     obj[1].showData();
  }
}

 

Step 2) Save , Compile & Run the Code.

Step 3) Error= ? Try and debug before proceeding to step 4.

Step 4) The line of code , Account obj[] = new Account[2] ; exactly creates an array of two reference  variables as shown below

java-array-of-objects

Step 4) Uncomment Line # 17 & 18. This step creates objects and assigns them to the reference variable array as shown below. Your code must run now.

 

java-array-of-objects-1

 

 

                                                 Back to Java Tutorials Index Page

 
 
Joomla 1.5 Templates by Joomlashack