Granny's Programming Pearls
"inside of every large program is a small program struggling to get out"
The moose likes Beginning Java and the fly likes Int By Reference passing.. Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of REST with Spring (video course) this week in the Spring forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Int By Reference passing.." Watch "Int By Reference passing.." New topic

Int By Reference passing..


Joined: Nov 20, 2004
Posts: 7
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

Joined: Jul 08, 2003
Posts: 24195

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().

[Jess in Action][AskingGoodQuestions]
Randall Julian

Joined: Nov 21, 2004
Posts: 14
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...
I agree. Here's the link:
subject: Int By Reference passing..
It's not a secret anymore!