xhtml
 

Declarations

So far, the programs we've seen have done their entire computation inside a single expression in the println call. For more complicated programs, we need to be able to declare and use variables. So far, we have only used simple integers. To declare a variable called n to hold an integer, we can write:

int n;

This is a declaration which tells Java to reserve some space, and says that we are going to call it n from now on. The type int means that the variable is an integer, i.e. it can only hold whole numbers. A couple of variations are worth mentioning. We can write:

int height, width, depth;

to declare several variables of the same type at once. Also, we can write:

int count = 10;

to declare a variable, and give it an initial value at the same time.

You may think it verbose to use long variable names like count rather than just c. However, in larger programs, there are typically hundreds or thousands of variables. If someone is going to be able to read and maintain a program without getting confused, especially if it is not the original author or it has been a long time since the code was written, the variables must have meaningful names. Single-letter names are only used for temporary working variables such as indexes which have no particular significance.


Back