Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trialKendhall Lebron Ruiz
Courses Plus Student 1,143 PointsSuper 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?
2 Answers
KRIS NIKOLAISEN
54,972 PointsThe 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
757 PointsI 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.
John McCracken
757 PointsJohn McCracken
757 PointsI just had the same question after watching it. Really confused too.