Dananjaya Gokhale Dananjaya Gokhale - 5 months ago 12
Java Question

Why below program is printing Object of different Array?

I am not able to understand the internal working that is happening behind the screen but I am confused because it is printing different result in console than what it is expected to. Could anybody resolve my problem with good explanation?

public class Demo {

public int [] sort(int h[])
{
int temp;
for(int i=0;i<h.length;i++)
{
for (int j=i;j<h.length;j++)
{
if(h[i]>h[j])
{
temp=h[i];
h[i]=h[j];
h[j]=temp;
}

}
}
return h;
}
public static void main(String args[])
{
Demo obj =new Demo();
int a[]={9,2,3,5,32,1,5,3,7};

int[] sorted=obj.sort(a);

/*Code to Display Array a*/
for(int s :a)
{
System.out.print(s+ " ");
}

System.out.println("");


/*Code to Display Array sorted*/
for(int k:sorted)
{
System.out.print(k+" ");
}
}

/*
Expected output
9 2 3 5 32 1 5 3 7
1 2 3 3 5 5 7 9 32

Actual output
1 2 3 3 5 5 7 9 32
1 2 3 3 5 5 7 9 32
*/


}

dpr dpr
Answer

The sort method is working on the actual input parameter that is passed to the method by call-by-reference (I know this is not 100% correct in terms of wording - see here). That is, all changes to the array h in sortare visible in the calling code as well.

If you don't want to change the input parameter, you need to make a copy of the object. In your case you could use System.arrayCopy to do so.