Click here to Skip to main content
15,921,530 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
hi every body!
I'm beginner in Java.
I have to write a method to exchange value of 2 integer number, that is:

C#
//......
public void swap(int a, int b){
        int temp = a;
        a = b;
        b = temp;
}
//...



It doesn't work, certainly! But I don't know the way to correct it. Please!
Thanks so much!
Posted
Updated 13-Mar-10 10:21am
v2

The reason why it doesn't work is that it doesn't swap the values of the integers you pass to the method. The method only swap the values of the two variables (a and b) that are declared in the method - it doesn't affect any variables outside of the method, even if they are passed as arguments to this method.

I did some Googling, and it seems it isn't that easy creating a swap method in Java, but I found the following site, which I hope you'll find useful.

Swapping in C, C++, and Java[^]
 
Share this answer
 
Sorry, but you cannot do that in Java. The only way to achieve what you want is to create a class that contains two integers and has a swap method to exchange them. Then all references to your integers would be through an instance of your class. Try rereading your Java documentation and thinking in terms of objects rather than primitive data types.
 
Share this answer
 
In java, every object is passed as reference to methods except primitive types like int, byte, Integer, Byte.(Sub. ed. Integer and Byte are also primitive type)

You could try to change the function to 'swap(int[] arr,int index1, index2)' and swap elements at specified indexes or you could pass objects to the method like swap(ObjectName a,ObjectName b) and swap objects' field values by something like :
VB
Integer tmp = a.value;
a.value = b.value;
b.value = tmp;
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900