Assignment

Now that we have created variables, we want to store values. We do that with an assignment statement.

bob = "Hello."; // give bob 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 deferent 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.

As a general rule, 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 bob.

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. For now you should remember the general rule, and we'll talk about exceptions later.

Another source of confusion is that some strings look like integers, but they are not. For example, bob 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.

bob = "123"; // legal
bob = 123; // not legal