java - Why below program is printing Object of different Array? -
i not able understand internal working happening behind screen confused because printing different result in console expected to. resolve problem explanation?
public class demo { public int [] sort(int h[]) { int temp; for(int i=0;i<h.length;i++) { (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 display array a*/ for(int s :a) { system.out.print(s+ " "); } system.out.println(""); /*code 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 */ }
the sort
method working on actual input parameter passed method call-by-reference (i know not 100% correct in terms of wording - see here). is, changes array h
in sort
are visible in calling code well.
if don't want change input parameter, need make copy of object. in case use system.arraycopy
so.
Comments
Post a Comment