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!

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

subhashree banik
subhashree banik
823 Points

Can someone please explain the order of this code?

String before = dispenser.swapHead("Darth Vader"); System.out.printf ("It was %s but Chris switched it to %s %n", before, dispenser.getCharacterName());

Here, before refers to Darth Vader and dispenser.getCharacterName() refers to Yoda. So the output should be " It was Darth Vader but Chris switched it to Yoda" but instead the output is "It was Yoda but Chris switched it to Darth Vader." WHY?

1 Answer

28,556 Points

Because you are incorrect about what the variables store. before stores what the dispenser.swapHead("Darth Vader") call returns. That method returns the name the dispenser had before it was switched. dispenser.getCharacterName() returns the current name of the dispenser, which was changed to "Darth Vader" by the swapHead method.

So before equals "Yoda" and dispenser.getCharacterName() equals "Darth Vader".

Sumit Doshi
Sumit Doshi
388 Points

Please explain in detail, I am finding difficult to understand