Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

What is passing by value?

 
Jake Miller
Ranch Hand
Posts: 43
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
What does it mean that Java is pass by value?
 
marc weber
Sheriff
Posts: 11343
Java Mac Safari
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
See this JavaRanch campfire story: Pass by value.
 
Jake Miller
Ranch Hand
Posts: 43
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks, pretty helpful. Another question re:

"In line 1, a cup called x, of size int, is created and given the value 3.

In line 2, a cup called y, of size int, is created and given the value... 3.

The x variable is not affected!

Java COPIES the value of x (which is 3) and puts that COPY into y. "

So in Java, if I type int x = 3, int y = x, it COPIES whatever x is and puts it into y. It's as if I right clicked on x and pasted it to y, right? How would I have y reference x, as in if I changed x it would also change y? (Like in excel when you reference another cell and change that cell...)
 
marc weber
Sheriff
Posts: 11343
Java Mac Safari
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Jake Miller:
...How would I have y reference x, as in if I changed x it would also change y? (Like in excel when you reference another cell and change that cell...)

That's a good question.

You cannot do this with Java primitive types, because the value itself is simply copied to the new variable. But if you want y to change whenever x changes, then maybe you don't need y at all. Just use x.

A more elaborate approach would be to replace y with a method that "gets" the current value of x when needed. This might be appropriate if x is an instance variable of some other object.
 
Jake Miller
Ranch Hand
Posts: 43
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by marc weber:

But if you want y to change whenever x changes, then maybe you don't need y at all. Just use x.



Oh yea. You could do that huh
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic