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 trialJonathan Sanders
752 PointsCan you instantiate a variable within method parentheses?
Looking at the exercise here, the first place we see the 'char tile' variable mentioned is inside the parameters of the 'addTile' method. Does the variable not need to be instantiated somewhere in the class first before it can be passed into the method?
(Please correct any inaccurately used terminology in my question!)
Many thanks.
public class ScrabblePlayer {
// A String representing all of the tiles that this player has
private String tiles;
public ScrabblePlayer() {
tiles = "";
}
public String getTiles() {
return tiles;
}
public void addTile(char tile) {
// TODO: Add the tile to tiles
}
public boolean hasTile(char tile) {
// TODO: Determine if user has the tile passed in
return false;
}
}
1 Answer
andren
28,558 PointsNo it does not have to exist to be used as a parameter name. In the parameter list of a method you state what type of argument you accept and what variable name you want that argument to have within your method. So by defining tile
in the parameter list you tell Java to take the first argument passed in and create a variable called tile
within your method that contains the contents of that argument.
You don't see the code that actually calls this method, but let's say it looks like this:
addTile('a');
With that code the tile
parameter would be set equal to a
within your method. The argument to parameter binding happens entirely based on their positions, so the first argument is bound to the first parameter and so on. The names doesn't really matter as far as the binding is concerned.