File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Beginning Java and the fly likes Passing primitive types by reference Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Passing primitive types by reference" Watch "Passing primitive types by reference" New topic

Passing primitive types by reference

Adam Zedan
Ranch Hand

Joined: Jun 10, 2011
Posts: 124

just a thought Is there any way by which i can pass primitive types by reference what do most most of the java gurus do to accomplish this??

Don’t look where you fall, but where you slipped
Henry Wong

Joined: Sep 28, 2004
Posts: 20535

Adam Zedan wrote:just a thought Is there any way by which i can pass primitive types by reference what do most most of the java gurus do to accomplish this??

No. In Java, references only points to objects. And primitives are not objects.

You can achieve this by having objects that contain primitives -- such as arrays of primatives or instances of classes that has instance variables of primative type.


Books: Java Threads, 3rd Edition, Jini in a Nutshell, and Java Gems (contributor)
Wouter Oet
Saloon Keeper

Joined: Oct 25, 2008
Posts: 2700

You can't. If you want something like that, create a class that wraps an primitive and use methods to change it. Or use a static variable but I don't recommend that since you can't control access to it.

"Any fool can write code that a computer can understand. Good programmers write code that humans can understand." --- Martin Fowler
Please correct my English.
Rob Spoor

Joined: Oct 27, 2005
Posts: 20276

There is no such thing as passing by reference, not even for objects. With objects, you pass a copy of the reference. This allows you to modify the object itself, but not the original reference itself.

How To Ask Questions How To Answer Questions
Luigi Plinge
Ranch Hand

Joined: Jan 06, 2011
Posts: 441

Put them in an array and pass (the value of the reference to) that.

But trying to pass primitives by reference is a weird thing to do - you can probably achieve what you want in a better way, if you explain what you're trying to achieve.
Stephan van Hulst

Joined: Sep 20, 2010
Posts: 4629

I agree with Luigi. There's never a good reason to do this. A much more robust way is to call a method that returns a primitive value based on the primitive you passed to it. The caller can then reassign the variable passed with the value returned. Avoid methods with side-effects if you can.

The mind is a strange and wonderful thing. I'm not sure that it will ever be able to figure itself out, everything else, maybe. From the atom to the universe, everything, except itself.
jQuery in Action, 3rd edition
subject: Passing primitive types by reference
It's not a secret anymore!