The Artima Developer Community
Sponsored Link

Legacy Java Answers Forum
July 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:

Passing objects to a method.

Posted by Igor on July 30, 2001 at 9:13 AM

Hello!
In Java all object pass to a method by reference. I have got th problem writing 'swap' method:

/// Code start
class Simple {
public int value;
}

class Swap {
public void swap(Simple obj1, Simple obj2) {
Simple temp = new Simple();

System.out.println(" Inside swap method.");
System.out.println(" obj1.value = " + obj1.value);
System.out.println(" obj2.value = " + obj2.value);

temp = obj1;
obj1 = obj2;
obj2 = temp;

System.out.println("obj1.value = " + obj1.value);
System.out.println("obj2.value = " + obj2.value);
}

public static void main(String [] args) {
Simple obj1 = new Simple();
Simple obj2 = new Simple();

obj1.value = 10;
obj2.value = 25;

System.out.println("Inside main method.");
System.out.println("obj1.value = " + obj1.value);
System.out.println("obj2.value = " + obj2.value);

swap(obj1, obj2);

System.out.println("After swap method.");
System.out.println("obj1.value = " + obj1.value);
System.out.println("obj2.value = " + obj2.value);
}
}
/// Code end

The program output was very surprised:

Inside main method.
obj1.value = 10
obj2.value = 25
Inside swap method.
obj1.value = 10
obj2.value = 25
obj1.value = 25
obj2.value = 10
After swap method.
obj1.value = 10
obj2.value = 25

If all object pass to a method by refference than after swap method its values should be changed... I don't understand why its didn't.
Could somebode explain me where is error?

Thank you.

I am sorry for a big message.




Replies:

Sponsored Links



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