Incremental Java
Expressions

What Do You Do with Expressions?

What do you do with expressions?

Evaluate them.

What do YOU do with expressions?

Evaluate them!

What do you DO with expressions?

EVALUATE THEM!

What is an Expression?

So far, we've looked at boxes. We've decided that types are important, so we give each box a type. A type is a set of possible values that can go in the box.

We can write to a box to change the value in the box. We can read from the box to see what value is in the box.

But this seems boring. Surely, we need the ability to do computation.

For example, suppose we want to compute 3 + 5. This is an expression. To evaluate such an expression is to find its value. Thus, 3 + 5 evaluates to 8.

The kind of expressions you create depend on the type. For example, you can add or multiply two int, but you can't multiply two char values.

Let's define expressions a bit more rigorously.

The first two expressions are "base" expressions. They are the simplest expressions we can create. The second two expressions are "inductive" expressions. They tell you how to make bigger expressions, from smaller expressions.

We know boxes have types, and because we can name boxes using variable names, then variable names have type too.

As we can see from the definition above, expressions have a type too. We'll talk about soon.

Here are some examples of expressions:

Unary vs. Binary Operators

A unary operator has a single operand. An operand is an expression. For example, in - x, the operand for - is x. The only unary operator you know is unary minus, which takes an int and produces a negated value.

A binary operator has two operands. It has a left operand (which is an expression) and a right operand (also an expression). Usually the types of the operands must match.

For example, in x + 10, the left operand is x while the right operand is 10.

There are four common binary operators: +, -, *, and /. This is addition, subtraction, multiplication, and division.

Interestingly, - is two different operators. Depending on the situation, it can be unary minus, as in - x, or it can be binary subtraction, as in x - y.

- is said to be "overloaded". This means that it has more than one meaning, depending on the situation.

Here's a quiz. Consider x - - - y. How many of the dashes are unary minus? How many are binary subtraction? And which are which?