0

I hope this is not a re-post. I couldn't find anything that answered my question so I decided to make this.

Say for example I have a

String [] arrayS = new String [2];

I assign the String arrays with words

arrayS[0] = Hello;
arrayS[1] = World;

Now I have a String [] method.

public static String [] change(String [] sArray, String newWord){
        //Do Stuff
    return sArray;
    }

So when I return the method, with or without the assignment operator, I still get the same result. Example...

//This result
String newWord = Hi;
arrayS = change(arrayS, newWord); // With assignment operator.
for(String word:arrayS)
    System.out.println(word);

//Is the same as this result
String newWord = Hi;
change(arrayS, newWord); // No assignment operator.
for(String word:arrayS)
    System.out.println(word);

Is there any reason why it is like this? I always thought you must have an assignment operator to something when you return. But when I print out the arrayS, it gave me the same thing doing both method.

NoobestPros
  • 65
  • 2
  • 8
  • 5
    I think you should take a look at [Is java pass by reference or pass by value](http://stackoverflow.com/questions/40480/is-java-pass-by-reference-or-pass-by-value), it might shed _some_ light on it. – takendarkk Nov 04 '16 at 03:11
  • It is a matter of preference in this case. The reference to the array you return should be the same one you already have in your calling code, so it is not necessary to return a reference. – Tim Biegeleisen Nov 04 '16 at 03:12

1 Answers1

1

You are not actually returning an object, you are returning a reference to an object.

public static String [] change(String [] sArray...

means that the method accepts a reference to a String[] and return a reference to a String[]. This also means that, even if these references are passed by value, any modification you do to sArray locally to change method it's reflected to the object itself.

There is no direct correlation between assignment operator and what you need to do. If the method returns a String[] then it means that it could return something different from the sArray passed, otherwise there's no reason to return anything at all, it just makes code less readable.

For example, returning a value could make sense when doing something like

String[] foo = new String[] {"foo"}
String[] bar = new String[] {"bar"};
String[] chosen = choose(foo, bar); // this method could return foo or bar

But doesn't make any sense in your situation, in which you reassign a value with itself making everything just more confusing.

It's is worth noting that these considerations doesn't apply to primitive types, which are values passed by value.

Jack
  • 131,802
  • 30
  • 241
  • 343