Next page | Contents page |

Identifiers, variables and constants

Identifiers

The names of classes, variables, methods, etc can begin with a letter, an underscore (_) or a dollar sign ($) and can then be followed by any number of letters, digits and/or underscores. Starting with _ or $ is unusual and you would do it to indicate something special, following a convention of your own.

Examples of valid names:

initialValue (for data - initial small)

get_initial_value (for a method - initial small but verb implies behaviour)

ItemValuer (for a class - initial capital)

When names are made up from several words it is common to use "camel case", as in the first and third examples above (it has humps!).

Variables

Memory locations in which values can be stored. In Java it is not possible to find out exactly where they are held in memory to get hold of their contents by any means except their name. So we declare a variable by stating its type and giving it a name:

boolean valuable;

Optionally assign a value at the same time:

boolean valuable = false;

The compiler will fail if you try to use the value of a variable and there is a route through the program whereby it could possibly not yet have been assigned one.

You can declare multiple variables of the same type in one statement:

int a, b, c;

but that is usually bad practice because it is often good to put a // comment to the right of each variable to explain its purpose.

Constants

If you use a fixed number in a program that you know is not going to change it is still good to give it a name (meaningful of course). In this case declare like a variable but do 2 things differently: (a) put the keyword final in front, which enables the compiler to fail if you subsequently try to change the value and (b) write the variable name all upper case, which alerts other programmers to the fact that it is constant (OK, it slightly goes against the rule that only classes start with capital letters but this is a very widely used convention). Eg,

final float CM_PER_INCH = 2.54;

final is an example of what Java calls a "modifier". public and static are modifiers too. Multiple modifiers on a single thing may occur in any order.

Next page | Contents page |