File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

swapping function

 
sigamala viswanath
Greenhorn
Posts: 26
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 6
Eclipse IDE Firefox Browser jQuery
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 23
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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)
 
Srivatsan santhanam
Greenhorn
Posts: 23
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Sorry a small typo

and pass reference of this Object/Bean and do the same swapping
 
ak pillai
author
Ranch Hand
Posts: 288
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I tend to agree with Ben Thurley. In case you need to do that, there are otherways to implement your swap function. godd discussion.
 
I agree. Here's the link: http://aspose.com/file-tools
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic