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

how to swap two integers inside a function ?

 
Lakshmi Geetha
Greenhorn
Posts: 16
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hi,
i have a function which takes two Integer's .the int values of them should be swapped when i return from the fn.
i tried doing Integer temp = i; i =j; j=temp. inside the fn. but when i come out and check the intValues()'s , they are not swapped.
could some one pls help me out ?
thanks
--lg.
 
Sri Bala
Ranch Hand
Posts: 63
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Lakshmi,
In C you'll have the prototype as
void swap( int *a, int *b )
In C++,
void swap( int &a, int &b )
There's nothing like this in Java. Arguments are always passed by value. In order to achieve that effect, you have to put it in an array or bundle it in an object and pass it to the function. Here's some code for you.
Sri!
class Wrapper
{
int aValue;
Wrapper(int value)
{
aValue = value;
}
public void setValue(int value)
{
aValue = value;
}
public int getValue()
{
return aValue;
}
}
public class Swap {

public void doSwap( int [] i, int [] j )
{
int k = i[0];
i[0] = j[0];
j[0] = k;
return;
}
public void doSwap( Wrapper a, Wrapper b )
{
int i = a.getValue();
a.setValue( b.getValue() );
b.setValue( i );
return;
}
public static void main(String [] args)
{
Swap swap = new Swap();
int [] a1 = { 10 };
int [] b1 = { 20 };
swap.doSwap( a1, b1 );
System.out.println(" a1, b1 = " + a1[0] + ", " +b1[0]);
Wrapper i1 = new Wrapper(100);
Wrapper i2 = new Wrapper(200);
swap.doSwap(i1, i2);
System.out.println("i1, i2 = " + i1.getValue() + " " +
i2.getValue());
}
}
 
Lakshmi Geetha
Greenhorn
Posts: 16
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
but isn't Integer an object ?
shouldn't it be passed by reference ?
All objects are passes by reference and all primitive types are passed by value in java , right ?

thanks for the sample code.
--lg
 
Frank Carver
Sheriff
Posts: 6920
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Yes, Integers are objects. No, Objects are not passed by reference. All parameters in Java are passed by value. When an object is passed as a parameter, a reference to the object is passed by value. What your simple swapping code was doing was swapping the references which will have no effect, as these references have been passed by value.
If you really want a "swap" routine, do it like this:
 
Lakshmi Geetha
Greenhorn
Posts: 16
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
thanks
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic