Win a copy of The Little Book of Impediments (e-book only) this week in the Agile and Other Processes forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Int By Reference passing..

 
SurferBoy
Greenhorn
Posts: 7
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
i have the following code:


how do i pass the int by ref..that the int value save the changes that the method caused??
 
Ernest Friedman-Hill
author and iconoclast
Marshal
Pie
Posts: 24212
35
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You can't. Java doesn't have pass-by-reference. It's not possible to write this sort of swap() method in Java, period.

Now, most of the time you want swap() in Java, you want to swap two elements in an array, and that's doable: you pass the array and the two indices as arguments to swap().
 
Randall Julian
Greenhorn
Posts: 14
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I am learning this stuff starting from C where the way you thought swap should work is reasonable. In Java, I think you have to take a different approach. This may be overly simplistic, but maybe someone will benefit from it (This is the "beginner" section after all):



The output is:

x = 1 y = 2
x = 2 y = 1
x = 5 y = 8
x = 8 y = 5

I thought there should be a way to use the Integer class to do exactly what you suggested. Java is all 'pass by value', but what gets passed for an object is it's reference since objects are all reference variables. This didn't work as I expected - more to learn I guess...
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic