1. public class Note {
2. public static void main(String args[]) {
3. String name[] = {"Killer","Miller"};
4. String name0 = "Killer";
5. String name1 = "Miller";
6. swap(name0,name1);
7. System.out.println(name0 + "," + name1);
8. swap(name);
9. System.out.println(name[0] + "," + name[1]);
10. }
11. public static void swap(String name[]) {
12. String temp;
13. temp=name[0];
14. name[0]=name[1];
15. name[1]=temp;
16. }
17. public static void swap(String name0,String name1) {
18. String temp;
19. temp=name0;
20. name0=name1;
21. name1=temp;
22. }
23. } // end of Class Note
Lets see if I can explain:
Line 4 : name0 is a ref to object "Killer" in the memory
Line 5 : name1 is a ref to object "Miller" in the memory
On line 6 function swap(name0, name1) is called and inside function swap(name0, name1) we pass copies of name0 and name1
so now the object and ref looks like
Main.name0 --- "Killer"
/
swap.name0 ---
Main.name1 --- "Miller"
/
swap.name1 ---
Inside swap we changed the values of swap.name0 and swap.name1 and do not change the values of main.name0 and main.name1 so now at the end of the function swap the ref looks like
Main.name0 --- "Killer"
/
swap.name1 ---
Main.name1 --- "Miller"
/
swap.name0 ---
Notice that the main.name0 and main.name1 are not changed so on line 8 it prints "Killer", "Miller"
Now in case of the other swap function the reference inside the function looks like
main.name ----- {"Killer", "Miller"}
/
swap.name ----/
Notice that both references point to the same object so when you make the swap of swap.name[0] and swap.name[1] the array changes to {"Miller", "Killer"}
and hence the output on the line 9 "Killer", "Miller"
Vinay