It's not a secret anymore!
The moose likes Java in General and the fly likes java passing variables by reference? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Java in General
Bookmark "java passing variables by reference?" Watch "java passing variables by reference?" New topic

java passing variables by reference?

Nikos Stavros
Ranch Hand

Joined: Feb 24, 2006
Posts: 243

is there a way to do this in java, like the following c++ code

Jesus lives
William Brogden
Author and all-around good cowpoke

Joined: Mar 22, 2000
Posts: 13037
Not the way you coded it. If you want to manipulate a bunch of int primitives and return the values, pass an array of int (a reference to an array object.)
Joanne Neal

Joined: Aug 05, 2005
Posts: 3742
As you are using a single method to process three ints, then we can assume those three ints are related in some way. If that is the case then they should be in a class.

This class should have a method called duplicate (double would be a better name) that doubles the value of each of the ints

Then your main method looks like this

If the three ints are not related in any way, then it is probably a bad design to have a single method processing them.
[ August 15, 2006: Message edited by: Joanne Neal ]

Rusty Shackleford
Ranch Hand

Joined: Jan 03, 2006
Posts: 490
No you can't do that. Everything in Java is passed by value.

"Computer science is no more about computers than astronomy is about telescopes" - Edsger Dijkstra
Ilja Preuss

Joined: Jul 11, 2001
Posts: 14112
While William's solution using an array would work, I find it to be a rather awkward workaround.

A goal of OO design is to put the data, and the operations on the data together in a class. Joanne's solution is one of the possible ways to do that.

The soul is dyed the color of its thoughts. Think only on those things that are in line with your principles and can bear the light of day. The content of your character is your choice. Day by day, what you do is who you become. Your integrity is your destiny - it is the light that guides your way. - Heraclitus
I agree. Here's the link:
subject: java passing variables by reference?
It's not a secret anymore!