• 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
  • Jeanne Boyarsky
  • Devaka Cooray
  • Paul Clapham
Sheriffs:
  • Tim Cooke
  • Knute Snortum
  • Bear Bibeault
Saloon Keepers:
  • Ron McLeod
  • Tim Moores
  • Stephan van Hulst
  • Piet Souris
  • Ganesh Patekar
Bartenders:
  • Frits Walraven
  • Carey Brown
  • Tim Holloway

How to write integer swap function in Java?

 
Greenhorn
Posts: 3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Forum,
While I know how to write integer swap function in c/c++ using pointer/reference, I don't know how to do this in Java since Java does not support passing basic data types by reference.
Also what is the reason for not allowing to pass basic data types by reference?
 
Ranch Hand
Posts: 1055
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Java has an Integer wrapper class that you can use, but Integer objects are immutable. Of course, you can always make your own Integer wrapper class...
All Java primitives are stored on the stack instead of the heap so you can only make local copies on different scopes. I'm not sure why this is designed this way...
 
Sheriff
Posts: 6920
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
there's been some discussion of this here before. A quick google found this old thread.
For me the bottom line has to be why do you want to do this? It just seems a wierd thing to want to do.
 
Wanderer
Posts: 18671
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I think it's an obvious thing to want to do when you're coming from a C background and haven't learned to think in Java yet. Essentially Prashant, you can't swap the contents of two arbitrary variables from another method. But if the variables are really just part of a larger data structure like an array or List, it's easy to swap elements within that larger structure. You just have to approach the problem from a different level. E.g. "write a method to swap elements i and j of List list:

[ July 25, 2002: Message edited by: Jim Yingst ]
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!