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

When was originalCharacterName declared?

class PezDispenser { private String characterName;

public PezDispenser(String characterName){ this.characterName = characterName; }

public String getCharacterName(){ return characterName; }

public String swapHead (String characterName){
  String originalCharacterName = this.characterName;
  this.characterName = characterName;
  return originalCharacterName;
}

} } How can "originalCharacterName" be used when it has not been declared yet? This is very confusing. And how does "this.character" differentiate between the two different types of "characterName" ?

originalCharacterName is declared in either another class that has access to this class or in another method. It gains access to the original declaration through the argument that is passed in public String swapHead (String characterName<<<<<<){ that means it pulls down the originalname into the method this.characterName = characterName; sets the character name that is pulled into the method to the one that is present in this class. It is saying this classes String originalCharacterName is now = to the one that got pulled in. Hope this helps.

2 Answers

It is declared in the method swapHead() when you declare a variable in a method it's a 'local variable' and only exists in the methods scope

Thank you so much !