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 trial

Java Java Objects Meet Objects Final

Tomasz Kaleta
Tomasz Kaleta
1,554 Points

Why String "before" gives an output "Yoda"?

Overall I understand the lesson. Just curious why this:

String before = dispenser.swapHead ("Darth Vader");

still gives an output "Yoda" when we define in printf method one variable as "before" shouldnt it be "Darth Vader" since this string = swapHead method that changes character name?

1 Answer

Steven Parker
Steven Parker
231,271 Points

You are quite right that the function changes the character name to "Darth Vader", but inside the function, the old name was saved as "originalCharacterName". That's the value the function returns, even though it has already changed it.

I suspect the variable being assigned was given the name "before" to indicate that it will be storing the name that was used before the switch. This is useful for creating the message that will show both the original name and what it was switched to.

Why wasn't the variable assigned in the code? It's definitely can become confusing when random variables come out of nowhere.

Steven Parker
Steven Parker
231,271 Points

The variable is assigned in the code, on line 10 (the line shown in the question). I'm not sure what you mean by "come out of nowhere".