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 trialDinu Comendant
6,049 PointsWhy getCharacterName gets different values?
PezDispenser dispenser = new PezDispenser("Yoda");
System.out.printf("This dispenser is %s %n",
dispenser.getCharacterName()
);
String before = dispenser.swapHead("Darth Vader");
System.out.printf("It was %s but now is %s %n", before, dispenser.getCharacterName());
in the first dispenser.getCharacterName we get Yoda, but in the second we get Darth Vader, why is that? the value of Yoda was transferred to originalCharacterName, so in the method getCharacterName it should return Darth Vader
1 Answer
Gregorio Massara
3,544 PointsThe answer I think is in the swapHead method;
public String swapHead (String characterName) {
String originalCharacterName = this.characterName;
this.characterName = characterName;
return originalCharacterName;
}
it returns the originalCharacterName but it also assigns it to the new Character in our case Darth Vader. Hence the confusion...and the need to use the final attribute for the original character to prevent this sort of changes.