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

andren
andren
28,465 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