JAVA regarding a particular method -


this question has answer here:

i got java test paper , there 1 question has been bugging me.

there question:

what output of following program?

public class swap {     public static void swap(int[] a){         int temp = a[1];         a[1] = a[0];         a[0] = temp;     }      public static void main(string[] args){         int[] x = {5,3};         swap(x);         system.out.println("x[0]:" + x[0] + " x[1]:" + x[1]);     } } 

the thought first came mind trick question. since swap method return type void, thought had no effect on int[] x array. answer x[0]:5 x[1]:3. got correct answer , when saw had been marked wrong, got confused. went try out actual code on netbeans , realized values in array got swapped! went on test if case string. typed in similar different code:

public class switch {     public static void switch(string s){         s = "goodbye";     }      public static void main(string[] args){         string x = "hello";         switch(x);         system.out.println(x);     } } 

the output still printed hello instead of goodbye. question why method not change string changes values inside array?

in java - "references objects passed value".

public class swap {     public static void swap(int[] a){  // = x --> {5,3}         int temp = a[1];          a[1] = a[0];     // swapping a[0] , a[1] in , next step.         a[0] = temp; // a[] goes out of scope since both x , pointing "same" object {5,3}, changes made reflected in x i.e, in main method.     }      public static void main(string[] args){         int[] x = {5,3}; // here - x reference points array {5,3}         swap(x);            system.out.println("x[0]:" + x[0] + " x[1]:" + x[1]);     } } 

and,

public class switch {     public static void switch(string s){ // s=x="hello"         s = "goodbye";   //here x="hello" , s ="goodbye"  i.e, changing "s" point different string i.e, "goodbye", "x" still points "hello"     }     public static void main(string[] args){         string x = "hello";         switch(x);         system.out.println(x);     } } 

Comments

Popular posts from this blog

apache - Remove .php and add trailing slash in url using htaccess not loading css -

javascript - jQuery show full size image on click -