In the code below I have mentioned that how can u copy an array. Try reading the comments in code, they are helpful.
class Main
{
public static void main(String arg[])
{
int a[] = { 25,10,45,20,15 };
int b[];
b=a; //creates a copy of reference i.e both a and b are referencing to the same array !
System.out.println();
for(int i=0;i<a.length;i++)
System.out.println(a[i]+"\t"+b[i]); //prints the same values of a and b because both are referring to the same array !
a[1] = b[3] = 0; // assigned some values
System.out.println();
for(int i=0;i<a.length;i++)
System.out.println( a[i]+"\t"+b[i] );
b=a.clone(); // to create a copy of array
a[1] = 50; // observe the assigned values
b[3] = 90; // observe the assigned values
System.out.println();
for(int i=0;i<a.length;i++)
System.out.println(a[i]+"\t"+b[i]); //COPY OF ARRAY DISPLAYED
}
}
class Main
{
public static void main(String arg[])
{
int a[] = { 25,10,45,20,15 };
int b[];
b=a; //creates a copy of reference i.e both a and b are referencing to the same array !
System.out.println();
for(int i=0;i<a.length;i++)
System.out.println(a[i]+"\t"+b[i]); //prints the same values of a and b because both are referring to the same array !
a[1] = b[3] = 0; // assigned some values
System.out.println();
for(int i=0;i<a.length;i++)
System.out.println( a[i]+"\t"+b[i] );
b=a.clone(); // to create a copy of array
a[1] = 50; // observe the assigned values
b[3] = 90; // observe the assigned values
System.out.println();
for(int i=0;i<a.length;i++)
System.out.println(a[i]+"\t"+b[i]); //COPY OF ARRAY DISPLAYED
}
}
No comments:
Post a Comment