Originally posted by satya kiran:
What is the output of the following class? Is the result because
strings are immutable or pass by value/reference?? Please explain (i always get confused with this question)
public class Bar {
private static String a;
private static void foo(String a){
a = "second";
}
public static void main(String[] argv){
a = "first";
System.out.println(a);
foo(a);
System.out.println(a);
}
}
Remember that all parameter passing in
Java is by value. When the formal parameter is an object reference, then a copy of the actual reference is sent to the method. You can access the original object through the formal parameter name as long as you don't change what the formal parameter points to.
Also in the case of String, you aren't able to change anything about the String because it is immutable so no matter what you do with the formal parameter it won't change the original object.