aspose file tools*
The moose likes Java in General and the fly likes swapping function Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Java in General
Bookmark "swapping function" Watch "swapping function" New topic
Author

swapping function

sigamala viswanath
Greenhorn

Joined: Mar 13, 2006
Posts: 26
Hi all,

This is my first mail to the group,
i have a question as follows:

class test
{
public static void main(String arg[])
{
String str1="Hello";
String str2="world";
test.swap(str1,str2);
System.out.println(" Swapped values are :"+ str1+str2);
}
static void swap( String str1,String str2)
{
String temp;
temp=str1;
str1=str2;
str2=temp;
}
}

what i had expect from here is i want to swap the two variable and print the value, i know clearly above function will not print the swapping values due to call by value.

my question here is how can we do the swapping of variable if java does not suppose call by reference ?

only way i got the solution is make str1 and str2 as class level static variable then it works fine.

but i am expecting any other alternatives for the above question.

i done some research on google to find out the answers but i am uable to get clear answers for it.

please help me out.

Thanks,
sigamala
Ben Thurley
Greenhorn

Joined: Oct 24, 2005
Posts: 6

I remember someone saying to me a couple of months ago that Java sucked because you can't write a swap function. A bit of googling turned up several explanations but the easiest to understand was at JavaWorld.

I have to say Ive been programming Java for three years and not once have I had to write a swap function.

Hope this helps
Ben
Srivatsan santhanam
Greenhorn

Joined: Jan 04, 2006
Posts: 23
Make Str1 and Str2 attributes of a Bean.

and pass reference to this Object and do the same swapping.
As only Object references are passed by value, you achieve the same.

(But no good programmer would do it this way...!!, unless there is a pressing need to do so)


Java Objects passed by Reference ?? -> you are a failure !!
Srivatsan santhanam
Greenhorn

Joined: Jan 04, 2006
Posts: 23
Sorry a small typo

and pass reference of this Object/Bean and do the same swapping
ak pillai
author
Ranch Hand

Joined: Feb 11, 2006
Posts: 288
I tend to agree with Ben Thurley. In case you need to do that, there are otherways to implement your swap function. godd discussion.


java j2ee job interview questions with answers | Learn the core concepts and the key areas
 
jQuery in Action, 2nd edition
 
subject: swapping function