Local variables and assignment

Local variables

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:

{
 if (Beh.getTexture() == Beh.HARD)
    Beh.say("I'm facing a rock.");
 else if (Beh.getTexture() == Beh.SOFT)
    Beh.say("I'm facing a plant.");
 else if (Beh.getTexture() == Beh.SPINY)
    Beh.say("I'm facing a predator.");
 else
    Beh.say("I'm not facing anything.");
}

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.

{
 int texture = Beh.getTexture();

 if (texture == Beh.HARD)
    Beh.say("I'm facing a rock.");
 else if (texture == Beh.SOFT)
    Beh.say("I'm facing a plant.");
 else if (texture == Beh.SPINY)
    Beh.say("I'm facing a predator.");
 else
    Beh.say("I'm not facing anything.");
}

Variable declarations

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.

Assignments

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.

{
 int odor = Beh.getNearbyOdor();
 int angle;

 if (odor == Beh.FOUL)
    angle = 3;
 else if (odor == Beh.SWEET)
    ongle = 5;
 else
    angle = 1;

 Beh.turn(angle);
 Beh.move();
}

Home

Calendar

Coursework & grading

Assignments

Lecture notes

Other resources


IU home

IU CS home

Contact instructor