Java Java Objects Meet Objects Final

Magdalena Frankowska
Magdalena Frankowska
15,501 Points

swapHeads - why new String ?

We have this part:

public String swapHead(String characterName) { String originalCharacterName = this.characterName; this.characterName = characterName; return originalCharacterName; }

but wouldn't it be the same if we did:

public String swapHead(String characterName) { this.characterName = characterName; return this.characterName; }

? I just don't understand why we need to create new String with originalCharacterName... Do we really need to keep this.characterName variable in a "safe place" as Craig said?

4 Answers

andren
andren
28,465 Points

The two methods you post will do different things:

public String swapHead(String characterName) {
 String originalCharacterName = this.characterName; // Store original characterName in originalCharacterName 
 this.characterName = characterName; // Change characterName to the one passed in to the method
 return originalCharacterName; // Return the original (old) characterName 
}
public String swapHead(String characterName) {
 this.characterName = characterName; // Change characterName to the one passed in to the method
 return this.characterName; // Return current (new) character name
}

Let's say characterName starts out as "Yoda" and you change it to "Vader". The first method would return "Yoda" while the second would return "Vader". If your purpose is to have the method return the original name then temporarily storing it in a variable like is done in the first example is indeed necessary.

Magdalena Frankowska
Magdalena Frankowska
15,501 Points

Thank you. At first all this code was a bit blurry for me but now I get it :)

HIDAYATULLAH ARGHANDABI
HIDAYATULLAH ARGHANDABI
20,998 Points

constructors are important part of programming Magdalena

If you want a more higher level answer: What happens is that when you create the String originalCharName, you are creating a pointer to this.charName. A pointer is basically just like an address. Think of it as a home address. The variable this.characterName has a home address which is stored in originalCharName. What happened when we said this.characterName = characterName , is that we basically told originalCharName that: "hmm, it looks like this.characterName has moved and now has a new address. Let me update the address of this variable. Since the address of this.characterName is now different, it "points" to a new value. i.e. the parameter you passed in. I know it seems a bit complex, but you'll eventually understand the lower level workings of Java. Hope this clears something :)