Java Java Objects Meet Objects Final

Kendhall Lebron Ruiz
PRO
Kendhall Lebron Ruiz
Pro Student 1,143 Points

Super confused about swapHead method in lesson

I don't understand how the method works at all. How is it returning the original when it was literally just swapped? Like for example, "The first input was Yoda, but now it is Darth Vader". What is happening in that code?

John McCracken
John McCracken
757 Points

I just had the same question after watching it. Really confused too.

2 Answers

The code for swapHead is as follows

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

characterName is what is passed in. In this case "Darth Vader"

String originalCharacterName = this.characterName; . This stores the current name in originalCharacterName. In this case "Yoda"

this.characterName = characterName; This sets the current name to the name passed in. The current name is now "Darth Vader"

return originalCharacterName; The return value is the stored original name. In the case "Yoda"

John McCracken
John McCracken
757 Points

I see why I was so confused. I somehow missed putting in the line "return originalCharacterName;". Now with that line there, it makes sense. I was also initially confused about which this the "this.characterName" referred to. I had it backwards.