How to make clear that a parameter of a method serves as a return value?

Tags: , ,

Is there a way to show that a parameter of a method serves as return value?

If I want to return one value it is no problem:

public Set<Integer> addIntegerToSet(final int i) {
    Set<Integer> intSet = new HashSet<>();

    return intSet;

It’s easy to see that the method returns a set.

But if I want a method to return two values I need a workaround:

public Set<Integer> addIntegerToSet(final int i, Set<Integer> returnIntMap) {
    Set<Integer> intSet = new HashSet<>();


    return intSet;

These two pieces of code are just examples to illustrate my question and they have no practical use.

However, I want to make it obvious to the user that this set (returnIntMap) was manipulated as well. It is common practice to put a “final” in front of parameters that are not manipulated within a method, but this is not done consequently, not even in Java standard classes.

So, how do I show that returnIntMap is manipulated within the method, without just mentioning it in the java doc comments. Are there any conventions?


It is not directly possible in Java.

Java uses pass by value. Objects and Arrays are actually pointers, so even though it looks like pass by reference, actually the reference is passed as value. This means you can modify the object, but not the reference to it.

final is not used that much, because it merely states that the pointer cannot be modified, but the object it points to can. Thus there is not much use to declare arguments to methods as final in a public interface. It is a nice safeguard in the actual implementation, though. In short: final != const and Java has no equivalent of const.

Even though you can technically only return one object, nothing stops you from returning a container that wraps several new objects into one.

If you just want to (internally) document which objects are modified you can use annotations to mark parameters as e.g. @ReadOnly or @ReadWrite. These are not part of the standard or any library I know, though there might very well exist one. Even if not, you can still define your own annotations.

Source: stackoverflow