Copying Arrays in JAVA


Copy Array in JAVA

In this lecturewe are going to see yet another impotant concep in arrays that is copying two arrays or copying one array into another.

let us consider an array

int []array1 = {2,4,6,8,10,15};

int []array2 =array1;    //copy memory location of array1 into array2, so both array point to same location. and thus both array will have sae values.

But, remember this is not copying array. this is copying address of on into another. It does not copy values.

You can now print these if you print the two by comparing

int []array1={2,4,6,8,10};    //declare an array with five elements

int []array2=array1;   //assign memory location of one into another, so both point to same location

printArray(array1);  //call to print array values

printArra(array2);   //call to print array values

……… more coding

//now the function definition

public static void printArray(int []array)

{

for(int value : array1)

{

System.out.println(value);

}

}

Now let us change some index value of array1 and print value of both array, well the value get reflected for array2 as well giving us illusion that array1 has been copied to array2. This is only because both objects point to same memory location.

So what is the correct method of copying two arrays

Step-1: make both arrays of same size, use array1.length as a way of making two arrays of same length

Step-2: use normal for() loop to place every single element of array1 and place it at the same index in array2 using the statement array2[i] = array1[i] inside the loop

Step-3[Optional]: print the value of two arrays using System.out.println() or JOptiopane.showmessageDialog().

Step-4[Optional] : if you change the value at some index of one array, it chages only in that array and noy=t in second array. This confirms that even though we have copied array1 into array2, both point to different memory address and independent.

Example- Complete program to copy an array into another array

package com.example;
public class arrays
{

public static void main(String[] args)
{

int []array1 = {2,4,6,8,10,15};
int []array2 =new int[array1.length]; //now both arrays are of same size and ={0,0,0,0,0}
for(int i=0; i<array1.length; i++)

{

array2[i] = array1[i];

}
//System.out.println(“Values in array1);
//System.out.println(array1);
//System.ut.println(“Values in array2: “);
//System.ut.println(array2);
System.out.println(“Values in array1”);
printArray(array1);
System.out.println(“Values in array2”);
printArray(array2);

}

public static void printArray(int []array)
{

for(int value: array)

{

System.out.println(value);

}

}

}

 

error: Content is protected !!