Evaluate them.
What do YOU do with expressions?
Evaluate them!
What do you DO with expressions?
EVALUATE THEM!
When Java sees an expression, it attempts to evaluate it. As a programmer, you must learn how expressions are evaluated too. While Java can evaluate expressions, you have to write the correct expression to be evaluated. If you don't know how to evaluate expressions, you won't discover your mistakes. Programming is just as much finding and fixing errors as it is creating code.
In the previous lesson, you learned that there are "base" expressions (literals and variables) and "inductive expressions" (built up using arithmetic or logical operators).
You write these expressions in Java, and then the program is "run" and these expressions get evaluated. Let's see how this works.
This is easy. Literals are pretty much values. When you see 7, it evaluates to 7. true evaluates to true.
OK, this isn't strictly true. The process of evaluation involves converting these numbers to binary numbers (0's and 1's) which have meaning to the computer, but has less meaning to you directly. Thus, 7 is converted to some binary number that stands for 7. You don't really have to worry about that for now, though.
Evaluating a variable is just reading the value inside the box. A variable has a variable name, which is just a shortcut to a box ID which contains the value you're interested in.
Thus, we might write env( "cost" ) and this function might return 10.
If the variable is not defined, we let the function return error.
The environment tells us what values variables have at different times in our program. Since we haven't seen a program yet, you don't know what this means.
Still, it's useful to mention environment now. For now, just think of it as something that tells you what values variables have.
We'll write out the environment like: [ "cost" = 10, "amt" = 20, "isValid" = true ]. This is a list with the variable name, an equal sign, and the value. We should write out the type of the variable, but hopefully you can tell the type by looking at its value.
Remember when we said there were two operations you could perform on a box? You could either read from a box or write to a box? In this case, we are reading a value from the box, and plugging the value in the expression, i.e., you replace the variable and put in its value instead.
Let's do a simple example. Assume that we have the following environment: [ "x" = 3, "y" = 4, "z" = 5 ]
The second step is to evaluate the expression to get a final value. The evaluated result is: 10.
Usually, we'll write it like an equation being solved:
(x * 2) + y ==> (3 * 2) + 4 ==> 6 + 4 ==> 10
3 + y * z ==> 3 + 4 * 5 ==> 3 + 20 ==> 23It's easy to make the mistake of adding 3 + y first, before multiplying. However, as in math, Java says "multiplication and division over addition and subtraction". This is known as precedence. We'll talk about precedence in another lesson.