[java] parameter passing:

Started by
3 comments, last by DDnewbie 22 years, 7 months ago
Hi, A simple question. What is the correct way of passing&retrieving objects in java? I mean, suppose you want to store a string in an object, and the name to store is passed as a parameter. Problem is, should you store the reference which is passed so that both the "outer" world and the object references the same String? If one stores the reference, a change in to the name in the object will also affect the outer worlds String (it's the same), and the outer-stuff wouldn't notice the change and thinks that the name is the same. Look at the code:
  
  String outer = new String("Outer treats this as constant");
  ...
  method(outer);

class object{
  private String owncopy; 
  
  void method(String param) 
  {
    //alternative one

    owncopy = param;   //DANGER!!

    //alternative two

    owncopy = new String(param);  // Only copy the "stringvalue"

  }
}  
See what I mean? A copy will be safe coz both have their own strings but initially with the same value. If alt 2 is the best/safest way, there seems to be much copying to be done when programming in Java! Any thoughts? /Mankind gave birth to God. Edited by - silvren on September 25, 2001 2:44:50 PM
/Mankind gave birth to God.
Advertisement
For strings just store the reference. A Java String object is immutable (meaning it can never change once it is created). If you want a string that you can modify use a StringBuffer.
Thanks for the reply.

But problem remains. String was just an example, it could have been MySpecialObjectThatIWantToChange.

That is, java has no equivalent thing such as "pass param value" which C/C++ does (automatic copying).
Well, java has that, but only for ordinary datatypes (int..).

Any more thoughts?



/Mankind gave birth to God.

Edited by - silvren on September 25, 2001 3:05:10 PM
/Mankind gave birth to God.
Normally you neither want to (because of performance reasons), nor have to, do much object copying so it makes sense to make pass-by-reference the default way to call methods. If you have to do some copying, you might want to check out the java.lang.Object.clone() method and the java.lang.Cloneable interface. The Cloneable interface is implemented in many classes in the JDK libraries and allows them to be copied using the clone method.

Henry
OK,

Thanks for the reply!
I'll read up on that stuff!

regards

/Mankind gave birth to God.

Edited by - silvren on September 25, 2001 5:09:01 PM
/Mankind gave birth to God.

This topic is closed to new replies.

Advertisement