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

Posted by Matt Gerrans on December 12, 2001 at 5:19 PM


> Of course 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..

In Java objects are always passed by reference. Primitives such as int, are passed by value.

You are passing by reference in both cases. In one case you are passing two Strings by reference, in the other you are passing one array by reference. The array is mutable, so you are able to swap its elements.

Keep in mind that Strings are immutable, so whether they are passed by value or by reference is kind of irrelevant for operational purposes. Of course, it is relevant for performance (memory and speed) purposes and that is why they are passed by reference. Passing an immutable object, like String, in Java is kind of like passing a const reference in C++: it is simple, safe and efficient.




Replies:

Sponsored Links



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