Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java is NEVER pass-by-reference, right?...right? [duplicate]

Possible Duplicate:
Is Java “pass-by-reference”?

I found an unusual Java method today:

private void addShortenedName(ArrayList<String> voiceSetList, String vsName)
{
     if (null == vsName)
       vsName = "";
     else
       vsName = vsName.trim();
     String shortenedVoiceSetName = vsName.substring(0, Math.min(8, vsName.length()));
     //SCR10638 - Prevent export of empty rows.
     if (shortenedVoiceSetName.length() > 0)
     {
       if (!voiceSetList.contains("#" + shortenedVoiceSetName))
         voiceSetList.add("#" + shortenedVoiceSetName);
     }
}

According to everything I've read about Java's behavior for passing variables, complex objects or not, this code should do exactly nothing. So um...am I missing something here? Is there some subtlety that was lost on me, or does this code belong on thedailywtf?

like image 797
Troy Nichols Avatar asked Apr 27 '09 20:04

Troy Nichols


People also ask

Is Java pass by or pass-by-reference?

Java is always Pass by Value and not pass by reference, we can prove it with a simple example.

Is there no pass-by-reference in Java?

Java doesn't support Pass by reference. Instead of passing only the value part of a variable, Java passes a reference to the original object for non-primitive. For primitive types, Java makes a copy of the variables and sends it to the function.

Is Java pass by value?

Java creates a copy of references and pass it to method, but they still point to same memory reference. Mean if set some other reference to object passed inside method, the object from calling method as well its reference will remain unaffected.

Does Java return by reference or copy?

Java does not support pass-by-reference (and return-by-reference).


2 Answers

As Rytmis said, Java passes references by value. What this means is that you can legitimately call mutating methods on the parameters of a method, but you cannot reassign them and expect the value to propagate.

Example:

private void goodChangeDog(Dog dog) {
    dog.setColor(Color.BLACK); // works as expected!
}
private void badChangeDog(Dog dog) {
    dog = new StBernard(); // compiles, but has no effect outside the method
}

Edit: What this means in this case is that although voiceSetList might change as a result of this method (it could have a new element added to it), the changes to vsName will not be visible outside of the method. To prevent confusion, I often mark my method parameters final, which keeps them from being reassigned (accidentally or not) inside the method. This would keep the second example from compiling at all.

like image 58
Michael Myers Avatar answered Oct 19 '22 20:10

Michael Myers


Java passes references by value, so you get a copy of the reference, but the referenced object is the same. Hence this method does modify the input list.

like image 32
Rytmis Avatar answered Oct 19 '22 18:10

Rytmis