• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Int By Reference passing..

 
Greenhorn
Posts: 7
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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??
 
author and iconoclast
Posts: 24207
46
Mac OS X Eclipse IDE Chrome
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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().
 
Greenhorn
Posts: 14
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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...
 
reply
    Bookmark Topic Watch Topic
  • New Topic