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
203,226 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.