by Dinesh Thakur

Just like simple variables can store different values at different times, an array variable can also be used to store a reference to different arrays at different times. Suppose you have created and initialized array variable num using the following statement,

int[] num = {5,15,25,30,50};

Suppose later on you want to use the array variable num to refer to another array containing 6 elements of int type then you can do this by simply writing the statement,

num = new int[]{10,20,30,40,50,60};

On execution of this statement, the previous array of 5 in t-type elements that is referenced by num is discarded and array variable num now references a new array of 6 values of type int.

Reusing Array Variables in Java Examples

public class ReusingArrayVariables 

{
          public static void main(String[] args)
      {
            int[] num= {5,15,25,30,50};
            System.out.println("Elements in Original Array : ");
            for(int i=0;i<num.length;i++)
                 System.out.print(num[i]+" ");
                 System.out.println("\nElements in New Array : ");
                 num=new int[]{10,20,30,40,50,60};
            for(int i=0;i<num.length;i++)
                 System.out.print(num[i]+" ");
      }
}

Reusing Array Variables in Java