Can someone explain to me what the reasoning behind passing by “value” and not by “reference” in Java is?

后端 未结 15 1405
[愿得一人]
[愿得一人] 2020-12-31 17:24

I\'m fairly new to Java (been writing other stuff for many years) and unless I\'m missing something (and I\'m happy to be wrong here) the following is a fatal flaw...

<
15条回答
  •  迷失自我
    2020-12-31 18:14

    Reference typed arguments are passed as references to objects themselves (not references to other variables that refer to objects). You can call methods on the object that has been passed. However, in your code sample:

    public static void thisDoesntWork(String foo){
        foo = "howdy";
    }
    

    you are only storing a reference to the string "howdy" in a variable that is local to the method. That local variable (foo) was initialized to the value of the caller's foo when the method was called, but has no reference to the caller's variable itself. After initialization:

    caller     data     method
    ------    ------    ------
    (foo) -->   ""   <-- (foo)
    

    After the assignment in your method:

    caller     data     method
    ------    ------    ------
    (foo) -->   ""
              "hello" <-- (foo)
    

    You have another issues there: String instances are immutable (by design, for security) so you can't modify its value.

    If you really want your method to provide an initial value for your string (or at any time in its life, for that matter), then have your method return a String value which you assign to the caller's variable at the point of the call. Something like this, for example:

    String foo = thisWorks();
    System.out.println(foo);//this prints the value assigned to foo in initialization 
    
    public static String thisWorks(){
        return "howdy";
    }
    

提交回复
热议问题