The Java Course provides a general introduction to programming in Java. It is based on A.B. Downey's book, How to Think Like a Computer Scientist. Click here for details.


Now that we have created some variables, we would like to store values in them. We do that with an assignment statement.

    fred = "Hello.";     // give fred the value "Hello."
    hour = 11;           // assign the value 11 to hour
    minute = 59;         // set minute to 59

This example shows three assignments, and the comments show three different ways people sometimes talk about assignment statements. The vocabulary can be confusing here, but the idea is straightforward:

  • When you declare a variable, you create a named storage location.
  • When you make an assignment to a variable, you give it a value.

A common way to represent variables on paper is to draw a box with the name of the variable on the outside and the value of the variable on the inside. This figure shows the effect of the three assignment statements:

For these diagrams I will use different shapes to indicate different variable types. These shapes should help remind you that one of the rules in Java is that a variable has to have the same type as the value you assign it. You cannot store a String in minute or an integer in fred. It would be like putting a square peg in a round hole.

On the other hand, that rule can be confusing, because there are many ways that you can convert values from one type to another, and Java sometimes converts things automatically. But for now you should remember that as a general rule variables and values have the same type, and we'll talk about special cases later.

Another source of confusion is that some strings look like integers, but they are not. For example, fred can contain the string "123", which is made up of the characters 1, 2 and 3, but that is not the same thing as the number 123.

    fred = "123";     // this is legal
    fred = 123;       // this is not legal

Last Update: 2011-01-24