Search code examples
javamethodsoutput-parameter

Output Parameters in Java


With a third party API I observed the following.

Instead of using,

public static string getString(){
   return "Hello World";
}

it uses something like

public static void getString(String output){

}

and I am getting the "output" string assigned.

I am curious about the reason of implementing such functionality. What are the advantages of using such output parameters?


Solution

  • Something isn't right in your example.

    class Foo {
    
        public static void main(String[] args) {
            String x = "foo";
            getString(x);
            System.out.println(x);
        }
    
        public static void getString(String output){
            output = "Hello World"
        }
    }
    

    In the above program, the string "foo" will be output, not "Hello World".

    Some types are mutable, in which case you can modify an object passed into a function. For immutable types (such as String), you would have to build some sort of wrapper class that you can pass around instead:

    class Holder<T> {
        public Holder(T value) {
            this.value = value;
        }
        public T value;
    }
    

    Then you can instead pass around the holder:

    public static void main(String[] args) {
        String x = "foo";
        Holder<String> h = new Holder(x);
        getString(h);
        System.out.println(h.value);
    }
    
    public static void getString(Holder<String> output){
        output.value = "Hello World"
    }