Win a copy of Kotlin in Action this week in the Kotlin forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

swap function in java  RSS feed

 
wrushasen dakhane
Ranch Hand
Posts: 47
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi all,

I want to write a swap function which will swap the values.

int a = 4, b = 5;
swap(a,b);
sop(a + " " + b);

output: 5 4

Please tell me how the swap function will be coded.
 
Nitesh Kant
Bartender
Posts: 1638
IntelliJ IDE Java MySQL Database
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Similar discussion here
The topic was about swapping string values, but it has details in general about it.
 
fred rosenberger
lowercase baba
Bartender
Posts: 12542
48
Chrome Java Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
if you had two glasses, one with water and one with milk, how would you swap the contents of the two glasses?
 
Garrett Smith
Ranch Hand
Posts: 401
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
A clever but stupid way:


This will actually swap the variables without creating a third variable.
[ May 05, 2007: Message edited by: Garrett Smith ]
 
Jim Yingst
Wanderer
Sheriff
Posts: 18671
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Fred, Garrett - that's not really going to help, is it? Not given they way the question has been asked.

wrushasen - in Java there is no way to do this. Not if a and b are local variables, and you're trying to swap them within a separate method. That's because the variables inside the swap method just get copies of a and b. Nothing you do inside swap will have any effect on the values a and b outside the swap method. The discussion Nitesh linked to is accurate.

If you want to do something like this, then you need to put the data into something besides local primitive variables. A common choice would be to put numbers in an array, then write a method to swap two elements (element i and j) of the array. E.g.

Output: 3 2 1 4

Try writing a swap() method that will swap two elements of the array, as shown.
 
Garrett Smith
Ranch Hand
Posts: 401
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I fixed my algorithm which was wrong. Duh.

I do feel that can be helpful to the original post, if you think about some examples.

Although I probably did give too much away.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!