home—info—lects—labs—exams—hws
tutor/PIs—breeze (snow day)
Object120 + its docs—java.lang docs—java.util docs
lect02b
local variables
-
Def'n: a variable is a labeled box.
Review examples of local variables from lect01c—values; variables,
and the accompanying memory diagram.
-
Convert pizzaArea, so that it uses a local variable.
-
From those, we can probably guess the general syntax:
- Syntax for declaring a local variable:
type name;
- Syntax for initializing a local variable:
name = expression;
N.B. the variable name must be on the left;
you can say n = 5 but not 5 = n.
You can see the “=” is not the same
as equality; it is actually describing an action:
Put the value into the box labeled n.
For this reason, I suggest:
tip:
Pronounce Java's “=” as “gets”
(as in “n gets 5”).
Some people like to read initialization statements (assignment statements)
right-to-left, since that's how the action works:
n = 2+3; means compute 2+3 (to get 5),
and then put 5 into the box labeled n.
-
N.B. Parameters are a special type of variable:
Really, you're kinda declaring them in the signature (see the similarity?),
and they get initialized for you automatically
-
To do, with your neighbor:
Complete the code for last3, whose test cases we wrote last time.
(Reminder: last3 takes in a String
and returns its last three letters.
We'll declare that the provided String must have
at least three letters.)
Variables vs. one-big-return
In class we'll write buffetPrice in two different ways:
using just one big return statement,
and another using a variable to store a subresult.
To do, with your neighbor:
Re-write at pizzaArea to use a variable.
To do:
Re-write last3 so that it uses just one big return statement.
home—info—lects—labs—exams—hws
tutor/PIs—breeze (snow day)
Object120 + its docs—java.lang docs—java.util docs