xhtml
 

Assignments

So far, we have usually declared a variable and initialised it all in one line:

int n = 42;
String result = "the answer is " + n;

This is really doing two things in one go. It is possible to do the declaration first, and then use an assignment to do the initialisation:

int n;
n = 42;
String result;
result = "the answer is " + n;

Assignments are used essentially to re-use variables, where that is a natural thing to do. For example, to find the sum of several numbers, say 23, 45, and 67 you might use a variable called total to hold a running total, like this:

int total = 0;
total = total + 23;
total = total + 45;
total = total + 67;

The assignment total = total + 23; tells Java to calculate the value total + 23 by finding the current value of the variable and adding 23 to it, then put the result back into the variable total as its new value. If you read it as "total equals total plus twenty-three", this sounds wrong, because the two sides are not equal. It is better to read the equal sign as "becomes", so the whole statement reads "total becomes total plus twenty-three".


Back