Response to a good question by Mr.Brophy

by Mike

In the post below my friend Mark posted this comment/question:

# Mark B. Says:
March 27th, 2007 at 7:22 pm e

That article was good.

But is Java always pass by value? Am I retarted? Has it really been over a year since I coded in Java? So many questionsÂ…

Now the answer to that question “But is Java always pass by value?” is more complicated than it seems. The first part of the answer is easy, in Java primitives are passed by value. Example

public void primTest(int x){
    x = 11;
}
 
 
int y = 1;
primTest(y);
 
System.out.println(y);

this does not print 11, it will print 1, because y was passed by value(thanks for the correction here Brian) as are all primitives in java.

Now here’s where the confusion comes, Objects appear to be passed by reference in Java but they are not, Objects are not passed at all. Let me explain. In Java we pass references to objects, basically a reference to an Object Instance. All variables in Java are either primitives or object references so its impossible to pass an object by reference.

Now thats kind of confusing because it still doesn’t answer the question. So the real answer here is that we pass everything by value but seeing that an Object reference is just a reference(The memory address of the Object) to an object when you pass an object reference by value to a method.

//note: I got this example(or at least the string buffer idea from an
//example of this on another web site, I honestly cant remember the 
//url so thats why theres no reference here)
 
StringBuffer sb = new StringBuffer("bleh");
 
passObject(sb);
public void passObject(Object o){
     o.append("bleh");
 
}

So the Object you modify in passobject is actually your String Buffer object and if you print your string buffer, you get “BlehBleh”.
(Finally after 2 years this is clear)

Anyway, I hope this answers your question Mark.
If it is unclear, I apologize, its not like me to get technical like this :P

-
Mike