Win a copy of Mesos in Action this week in the Cloud/Virtualizaton forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Swaping Primitive Data types in java

 
rohan yadav
Ranch Hand
Posts: 156
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi all,
I wants to swap primitive data types in java, as java uses pass by value for primitive data types , i used wrapper class and passed to the swap function still i am not able to swap the values can you please help...
Below is the code segment for the same....



 
Matthew Brown
Bartender
Posts: 4567
8
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Java uses pass by value for everything, it's just that for reference types it passes the reference by value. So you can't swap two references in the way you're trying.

(Even if you could, the fact that your method below involves auto-boxing and unboxing int to and from Integer would complicate matters - but that's not the real problem here).

If you want to swap a and b in the main method, you'll have to do it in the main method.
 
rohan yadav
Ranch Hand
Posts: 156
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Then how should i achieve pass by reference in java(as we do it in c++, i am from c++ background)
 
Jesper de Jong
Java Cowboy
Saloon Keeper
Posts: 15284
39
Android IntelliJ IDE Java Scala Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
There is no pass-by-reference in Java - there is no way to achieve pass-by-reference in Java, it's simply not possible.
 
Matthew Brown
Bartender
Posts: 4567
8
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You don't - it doesn't exist in Java. As I said, you can pass references around. But you can't pass a reference into a method and have it come back pointing at a different object.

You just have to do things in a different way.

You could get the effect by encapsulating the variables in an object, and pass a reference to that object. Not really worth it for swapping values, but it would look something like this:




 
Andrey Kozhanov
Ranch Hand
Posts: 79
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
It won't work this way. Wrapper classes for primitive types are still passed by value, and this classes are immutable (i.e. you can not change their state after creation). So the only way to change variable value by function is to wrap it in mutable class, like the following: and pass instance of this class to the function.
 
rohan yadav
Ranch Hand
Posts: 156
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Ohh .. Thanks Mathew and Andrey for your suggestions..
It seems that i have made a habit of thinking in c++ style
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic