• 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 all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Liutauras Vilda
  • Bear Bibeault
  • Jeanne Boyarsky
  • Tim Cooke
Sheriffs:
  • Knute Snortum
  • Junilu Lacar
  • Devaka Cooray
Saloon Keepers:
  • Ganesh Patekar
  • Tim Moores
  • Carey Brown
  • Stephan van Hulst
  • salvin francis
Bartenders:
  • Ron McLeod
  • Frits Walraven
  • Pete Letkeman

Swap function in java  RSS feed

 
Greenhorn
Posts: 16
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Can anyone show me how to write Swap funtion in java. I tried but its not working properly.COde will be help lot.
 
Ranch Hand
Posts: 1365
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If you're from a C++ background, you may be envisioning something like this:

Alas, you cannot have a method with precisely those semantics in Java.
You'll have to use a temporary variable to swap two variables.
If you'd like to swap two items in an array, you can just do what comes naturally:
 
Ranch Hand
Posts: 3451
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If you want to do it without a temporary holder check out this thread.
 
author & internet detective
Marshal
Posts: 38664
677
Eclipse IDE Java VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Just to elaborate on what David said:
You can't use a swap function with the semantics swap(int a, int b) because ints are passed by value, not by reference. If you want to swap the values of two objects, you can usually do that. You can also use the array as David explained.
If you are just using integers, it's less complicated to just do it in the code instead of in a separate function.
 
Greenhorn
Posts: 13
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hi,
here goes buddy...

 
Greenhorn
Posts: 20
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,
I've been thinking about how to swap boolean values without using helper variables but I think it is impossible to do it in a clever way. The only way I could come up with is this:

Regards,
Hans
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!