J
jt
hmmm... I thought I copied and pasted that code in line for line. IJoshua said:JT said:Practical Java Programming Guide Peter HaggarLew said:Wojtek wrote:
Chris Uppal wrote :
Wojtek wrote:
No it is a call by reference. If it was a call by value, then a clone
of the StringBuffer (in the following code) would be placed in the
stack. The method would then use the clone and the calling main()
would
still use its private copy.
So, taking the two points together, most Java programmers prefer to
stick very tightly to the low-level view of parameter passing and
state that Java /only/ has call by value, but that some of those
values are references to objects. Anything else is known to lead to
massive confusion.
When I read SCJP study materials, they have always asserted
unequivocally "call-by-value" as the only correct answer to "how does
Java pass method arguments?"
-- Lew
Praxis 1: Understand that parameters are passed by value, not by
reference
import java.awt.Point;
public class PassByValue {
public static void modifyPoint(Point pt, int j){
pt.setLocation(5,5);
j=15;
System.out.println("During modifyPoint " + "pt = " + pt t " and j
= " + j);
}
public static void main(String [] args) {
Point p = new Point(0,0);
int i = 10;
System.out.println("Before modifyPoint " + "p = " + p + " and i =
" + i);
modifyPoint(p, i);
System.out.println("After modifyPoint " + "p = " + p + " and i = "
+ i);
}
}
Here's what I get as output (after changing 'pt t' to 'pt +'):
Before modifyPoint p = java.awt.Point[x=0,y=0] and i = 10
During modifyPoint pt = java.awt.Point[x=5,y=5] and j = 15
After modifyPoint p = java.awt.Point[x=5,y=5] and i = 10
Primitive types are passed by value, *but* Objects are passed by
reference. Or, if you want to think of it like this, an Object is really
a pointer, so when you pass Objects, you are passing the address of the
Object.
must have messed up when I was trying to format the code to be included
inline. my bad....