简体   繁体   中英

what is the correct and best way to pass argument by reference to a method?

This is my code :

import java.util.LinkedList;

public class Main {


    public static void main(String[] args) {
        String str = new String("this is a text");
        System.out.println(str);
        getThis(str);
        System.out.println(str);

    }

    private static void getThis(String str) {
         str = "text changed"; 
    }

}

and the output is :

this a text
this a text

I want str change after the getThis method called.

I know I should pass str by reference, and I know that this can be done by declaring the str as static and out of the main method and then call it in the method like this Main.str . But is it the correct way and standard way to pass by reference?

Java is not pass by reference, it's always pass by value. And for references.

It's passing references as values to the caller. You can do it by returning the String value from getThis() method and assigned to the same variable

public class Main {


    public static void main(String[] args) {
        String str = new String("this is a text");
        System.out.println(str);
        str = getThis();
        System.out.println(str);

    }

    private static String getThis() {
         return "text changed"; 
    }

}

As others have stated Java is always pass by value with the slight caveat that when you pass in objects (like String) you are passing the value of a Reference to an object on the heap.

In your example, assignment has no effect outside the method and since Strings are immutable you can't really do much. If you passed in a StringBuilder then you could mutate the state of the object on the heap.

More generally instead of passing in an Object x you can pass in a wrapper object that contains a set method. Java provides an AtomicReference which allows you to do this.

In java, "references to objects are passed by value". So, any reference to a non-primitive object that you pass will be directly used and changes will be reflected in the original object.

Also, as a side note, Strings are immutable, so, you will get a new String if you try to change it (Strings cannot be changed), the original one will not be changed.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM