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

后端 未结 15 1463
[愿得一人]
[愿得一人] 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:02

    It is because, it creates a local variable inside the method. what would be an easy way (which I'm pretty sure would work) would be:

    String foo = new String();    
    
    thisDoesntWork(foo);    
    System.out.println(foo); //this prints nothing
    
    public static void thisDoesntWork(String foo) {    
       this.foo = foo; //this makes the local variable go to the main variable    
       foo = "howdy";    
    }
    

提交回复
热议问题