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);
}
Java is Strictly Pass by value.
Let's modify your code as below from the explanation point of view
static void swap(String str1, String str2){
String temp = str1;
str1=str2;
str2=temp;
}
public static void main(String[] args) {
String s1 = "Hello", s2 = "world";
swap(s1, s2);
System.out.println(s1 + s2);
}
S1 and S2 are the references which hold the address of the string object. For ex: S1=123 , S2= 234
When we call swap method, copy of S1 and S2 is created and will be assigned to str1 and str2.
Which will be str1=123 and str2=234.
Swap method will only swap the values present in str1 and str2. (str1=234 str2=123) whereas S1 and S2 still points to the same memory location.
This is the reason why the swap is not reflected in the main method.
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.
1. First and foremost thing, Java
is pass by Value
.( ie Pass by Copy).
2. You are passing the reference
Not the Object to the method.
Eg:
public class Test{
private String x;
public void go(String s){
this.x = s;
}
public static void main(String[] args){
Test t = new Test();
String a = new String("Bye");
t.go(a);
}
}
The above code is not to show how swapping is done, but to make an important point visible.
When go(String s)
method is called by passing an Argument "a" which is an Object reference variable
of type String to the Parameter "s" which is also an Object reference variable
of type String, its just the reference that is passed by Value / Copy.
Any changes done on the reference
will effect the String object on the Heap, NOT the reference
.
What gets passed to a method is a copy of the reference of the object. So, no matter how many times you re-assign the references, the original reference will not be affected.
Try this:
static void reverse(StringBuilder builder) {
builder.reverse();
}
public static void main(String[] args) {
StringBuilder builder = new StringBuilder("hello");
System.out.println(builder);
reverse(builder);
System.out.println(builder);
}
However, the below method wouldn't make any difference to the original object passed in.
static void swap(StringBuilder builder) {
builder = null;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With