• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Passing primitive types by reference

 
Adam Zedan
Ranch Hand
Posts: 124
C++ Fedora Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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??
 
Henry Wong
author
Marshal
Pie
Posts: 21515
84
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.

Henry
 
Wouter Oet
Saloon Keeper
Posts: 2700
IntelliJ IDE Opera
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Rob Spoor
Sheriff
Pie
Posts: 20669
65
Chrome Eclipse IDE Java Windows
  • Likes 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Luigi Plinge
Ranch Hand
Posts: 441
IntelliJ IDE Scala Windows
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Bartender
Posts: 6337
79
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic