File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
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
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Int By Reference passing.." Watch "Int By Reference passing.." New topic
Author

Int By Reference passing..

SurferBoy
Greenhorn

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
Marshal

Joined: Jul 08, 2003
Posts: 24184
    
  34

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
Greenhorn

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: http://aspose.com/file-tools
 
subject: Int By Reference passing..