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

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

    This is because inside "thisDoesntWork", you are effectively destroying the local value of foo. If you want to pass by reference in this way, can always encapsulate the String inside another object, say in an array.

    class Test {
    
        public static void main(String[] args) {
            String [] fooArray = new String[1];
            fooArray[0] = new String("foo");
    
            System.out.println("main: " + fooArray[0]);
            thisWorks(fooArray);
            System.out.println("main: " + fooArray[0]);
        }
    
        public static void thisWorks(String [] foo){
            System.out.println("thisWorks: " + foo[0]);
            foo[0] = "howdy";
            System.out.println("thisWorks: " + foo[0]);
        }
    }
    

    Results in the following output:

    main: foo
    thisWorks: foo
    thisWorks: howdy
    main: howdy
    

提交回复
热议问题