The Artima Developer Community
Sponsored Link

Legacy Java Answers Forum
January 2001

Advertisement

Advertisement

This page contains an archived post to the Java Answers Forum made prior to February 25, 2002. If you wish to participate in discussions, please visit the new Artima Forums.

Message:

Swapping of two Object Variables.

Posted by Mohamed Ibrhaim on December 12, 2001 at 5:23 AM

Hi,
Ofcourse the code does work fine. But explain me the difference between following two different programs. One uses pass by reference and other pass by value.. Why this contradiction? In both i use string objects..

1.
class Test
{
public void swap(String x, String y)
{
String temp = x;
x=y;
y=temp;
}
public static void main(String args[])
{
String xx = new String("Mohamed");
String yy = new String("Ibrahim");
Test t0= new Test();
System.out.println("The value of x and y before swap are "+xx+", "+yy);
t0.swap(xx,yy);
System.out.println("The value of x and y after swap are "+xx+", "+yy);
}
}

2.

class Swapp{
public void swap(String[] x)
{
String temp = x[0];
x[0] = x[1];
x[1] = temp;
}
public static void main(String[] args)
{
Swapp sp= new Swapp();
String x[]= new String[]{new String("Mohamed"), new String("Ibrahim")};
System.out.println("x[0]=" + x[0] + " x[1]=" + x[1]);
sp.swap(x);
System.out.println("x[0]=" + x[0] + " x[1]=" + x[1]);
}
}





Replies:
  • Swapping Matt Gerrans December 12, 2001 at 5:19 PM (0)
  • Swapping Matt Gerrans December 12, 2001 at 5:19 PM (0)

Sponsored Links



Google
  Web Artima.com   
Copyright © 1996-2009 Artima, Inc. All Rights Reserved. - Privacy Policy - Terms of Use - Advertise with Us