Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java String immutable passed by reference/value

Tags:

java

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?

Thanks!

public class Test {

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

    public static void f(String b){
        b+="de";
        b=null;
    }
}
like image 371
Taobitz Avatar asked Feb 16 '13 23:02

Taobitz


2 Answers

The line b+="de"; in the void f(String b) functions creates a completely new object of String that does not affect the object in the main function.

So when we say String is immutable when mean any change on a String object will result in creating a completely new String object

public class Test {
    public static void main(String[] args){
        String a =new String("abc");

        String b = a; // both a & b points to the same memory address

        f(b); // has no effect

        // b still has the value of "abc"
        b+="fg" // a new String object that points to different location than "a"

        System.out.println(a + " " + b); // should print "abc abcfg" 
    }

 public static void f(String b){
    b+="de";  // creates a new object that does not affect "b" variable in main
    b=null;
 }
}
like image 167
iTech Avatar answered Sep 29 '22 07:09

iTech


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.

like image 40
Bohemian Avatar answered Sep 29 '22 09:09

Bohemian