splinter123
splinter123

Reputation: 1203

Java memory management mystery

I have this piece of code inside a static method of a Java program:

import org.w3c.dom.Document;
...
Document tempdoc1=tempdoc;
//tempdoc1=xmlModifier.setMacro(tempdoc, liquidity, "liquidity"); // this slightly modifies the document
tempdoc1=null;
if (tempdoc1==null){
tempdoc1=tempdoc;
} 
...do something with tempdoc1

What I don't understand is the following: if I take out the comment "//" I get a different result from the subsequent execution of the code, while from my basic understanding it should be exactly the same, since in any case the variable tempdoc1 is redefined at the following line! Does anybody know why?

EDIT: I don't see how the static method setMacro of the class xmlModifier can modify the object referenced by tempdoc. For example this code

public static void main(String[] args) {
    String test="test";
    String test2=dosomething(test);     
    System.out.println(test);

}

public static String dosomething(String str){
    str="mod";
    return str;
}

simply prints "test", i.e. the method dosomething does not modify the object referenced by test. Are there situations where this is not the case?

Upvotes: 0

Views: 76

Answers (1)

Jon Skeet
Jon Skeet

Reputation: 1502176

Well presumably the statement:

xmlModifier.setMacro(tempdoc, liquidity, "liquidity");

has some effect on xmlModifier, or tempdoc, or liquidity - so with that commented out, you don't see that effect.

My guess is that the method modifies tempdoc and then returns it, and you're expecting it to return a copy. Objects in Java don't work that way. In fact, it wouldn't modify tempdoc at all - it would modify the object that the value of tempdoc refers to. If the method returns a reference to the same object, that doesn't create a new object - it just means you've got two references to one object, like two pieces of paper each with the same house address on.

Upvotes: 1

Related Questions