Karl Boyle Karl Boyle - 11 months ago 38
Java Question

Java String immutable passed by reference/value

Hi Im studying for my scja exam and have a question about string passing by ref/value and how they are immutable. The following code outputs "abc abcfg".

What I want to know is why is this happening? Im not understanding what happens inside of method f. String is passed by value so surely it should change to "abcde" inside the method? Because if b+="fg" appends to the string why doesnt it work inside the method?


public class Test {

public static void main(String[] args){
String a =new String("abc");
String b = a;
System.out.println(a + " " + b);

public static void f(String b){

Answer Source

In your method f() you are assigning a new String to the parameter b, but parameters are just like local variables, so assigning something to them has no effect on anything outside the method. That's why the string you passed in is unchanged after the method call.