Win a copy of Think Java: How to Think Like a Computer Scientist this week in the Java in General forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

JavaRanch Roud-up - #203

 
Wagner Danda
Greenhorn
Posts: 26
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
"(#203)When you pass a variable as an argument to a method call, what are you passing?
Answer: a copy of the value
You always get a copy of whatever is in variable -- either a primitive or a reference. So for objects, you get a copy of the reference."
Is this true? See this example:
class Xxx {
public void incY(Yyy obj) {
obj.id++;
}
}
class Yyy {
public int id = 0;
}
public class TestXxx {
public static void main (String[] args) {
Yyy Yobj = new Yyy();
Xxx Xobj = new Xxx();
System.out.println("Before: " + Yobj.id);
Xobj.incY(Yobj);
System.out.println("After: " + Yobj.id);
}
}
This prints:
"Before: 0
After: 1"
So... Did I forget about something?
[]�s
Wagner Danda
 
leena rane
Ranch Hand
Posts: 280
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator


You always get a copy of whatever is in variable -- either a primitive or a reference. So for objects, you get a copy of the reference."
Is this true?

yes this is absolutely true.
When arguments are pased,a copy of value is passed


class Xxx {
public void incY(Yyy obj) {
obj.id++;
}
}
class Yyy {
public int id = 0;
}
public class TestXxx {
public static void main (String[] args) {
Yyy Yobj = new Yyy();
Xxx Xobj = new Xxx();
System.out.println("Before: " + Yobj.id);
Xobj.incY(Yobj);
System.out.println("After: " + Yobj.id);
}
}
This prints:
"Before: 0
After: 1"
So... Did I forget about something?
[]�s

I have not understanood your question,
i suppose this(from explantion) is what should answer your question
"So for objects, you get a copy of the reference."
if u still have doubt,most welcome !!
 
Asma Zafar
Ranch Hand
Posts: 49
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
In java the arguments are always passed by value. But always remember that when the reference to an object is passed as an argument, the reference itself never changes but with the help of this refrence the value of instance/static variables can always be changed.
This is why the output represented by your code is 1 after you passed the reference to the object of YYY.
Hope this helps,

------------------
Asma Zafar,
Sun Certified Programmer for Java2 Platform
 
Wagner Danda
Greenhorn
Posts: 26
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Humm... I think I made a mistake. I was thinking about "copy of the value", and no "copy of the reference". Thanks for the help!

[This message has been edited by Wagner Danda (edited September 08, 2001).]
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic