Sometimes we need to refer to the same piece of data more than one time within the body of a particular method. For example, say we want to find the texture of the cell the critter is facing and then do several different things with this number within the body of a method. We could do the following:
The trouble with this version is that it calls Beh.getTexture()
three times.
This could be quite expensive.
What we'd prefer is to save the result of calling this method once and then
use this each time we need it, without called the method again.
For this purpose we can use a variable.
A local variable provides us with a location to store some value.
Here is how the above code would look with a local variable.
When we create a variable, we need to declare it by giving a type and an identifier
for it.
In the example above a variable with the identifier texture and
the type int.
By convention, variables in Java have lowercase identifiers.
Since a declaration is a statement, it must be followed by ;.
A local variable is valid only within a particular block (a series of statements
between { }) or with a for expression (which we will learn about later).
It is declared at the beginning of the block.
When the code within that block is entered while the program is running, a new
variable is created.
When the execution of the block is complete, the variable effectively ceases to exist.
No reference to it can be made outside the block where it was declared.
To assign a value to a variable, we use the assignment operator =.
The variable's identifier appears to the left of the operator and the value to the
right.
We can assign a value to a variable when it is first declared, as in the example above,
or later within the block or for expression where it was declared.
Here is a more complicated example with two local variables.