Incremental Java
Boxes and Values

Boxes and Values

Let's start simple. Imagine you have a box. It's really a square. Draw one on a piece of paper.

We're going to have some rules about boxes. First, it can only hold one value. For now, a value is a whole number. It can be positive, negative or zero.

Second, we can only do two operations with boxes. We can either read from a box, or write to a box.

Just to make sure you're keeping up, answer the following easy question. What two operations can we perform on a box?

Reading

What does it mean to read from a box? It means to ask the box for its current value. I can ask "what value is in the box", and the answer might be, say, 10.

Why do we read from a box? Can't we just "look" at a box to determine what value is in it? First of all, computers don't have eyes. They can't "see" anything. They can, however, request the value from a box. Secondly, even humans have a similar problem. You might be asked "What is the first word of page 316 of the Hitchhiker's Guide to the Galaxy". You have to go look up page 316 to find it. Similarly, computers have to look up values too.

Writing

What does it mean to write to a box? It means to replace the value in the box with a new value. For example, if you write 3 to a box, and it previously had 10, it now has 3. The 10 is gone. You can't get it back. That's what we mean by saying a box has just one value.

What if the box had the value 10, and you write 10 to the box? It keeps the same value. There is no error.

Recap

Explain, in your own words, what reading and writing to a box means.

An Analogy

If you've ever used a spreadsheet, you know it's made of a grid of cells. You can think of one cell as the same as a box. It's a place to store one value.

Exercise

Here's an exercise. I'll list out a series of read or write operations. If I say "Write 7", then you replace the value of the box with 7. If I say "Read", you tell me what's in the box. We'll assume the box is initially 0.

This is a very easy exercise. The easiest way for you to do this is to have a piece of paper, draw a box, put a value of 0 inside the box. Each time you do a write operation, cross out the old value, and put in the new value. It's OK if you draw outside the box when doing this.

Each time you do a read operation, you tell me what's in the box.

Let's begin:

  1. Read
  2. Write 7
  3. Write 3
  4. Read
  5. Write -1
  6. Read
  7. Read
  8. Write 10
  9. Read

Solution

Solutions are written in red
  1. Read Value is 0
  2. Write 7
  3. Write 3
  4. Read Value is 3
  5. Write -1
  6. Read Value is -1
  7. Read Value is -1
  8. Write 10
  9. Read Value is 10
Pretty simple, right? Notice that step 6 and 7 give the same answer because we did not change the value of the box during these two steps.