Monday 30 January 2017

pass by reference - swapping of objects in java




I have studied that java is pass by reference but when I execute following code the strings are not swapped in main method why?




static void swap(String s1, String s2){
String temp = s1;
s1=s2;
s2=temp;
}

public static void main(String[] args) {
String s1 = "Hello", s2 = "world";
swap(s1, s2);

System.out.println(s1 + s2);
}

Answer



You studied wrong sources. Java is pass by value. Here is one source more you can study. And from here you can find discussion about example similar to yours.


No comments:

Post a Comment

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...