Home > Articles > Programming > Java

  • Print
  • + Share This
This chapter is from the book

Variables

In Java, every variable has a type. You declare a variable by placing the type first, followed by the name of the variable. Here are some examples:

double salary;
int vacationDays;
long earthPopulation;
char yesChar;
boolean done;

Notice the semicolon at the end of each declaration. The semicolon is necessary because a declaration is a complete Java statement.

The rules for a variable name are as follows:

A variable name must begin with a letter, and must be a sequence of letters or digits. Note that the terms ”letter” and ”digit“ are much broader in Java than in most languages. A letter is defined as 'A'–'Z', 'a'–'z', '_', or any Unicode character that denotes a letter in a language. For example, German users can use umlauts such as 'ä' in variable names; Greek speakers could use a π. Similarly, digits are '0'–'9' and any Unicode characters that denote a digit in a language. Symbols like '+' or '©' cannot be used inside variable names, nor can spaces. All characters in the name of a variable are significant and case is also significant. The length of a variable name is essentially unlimited.

If you are really curious as to what Unicode characters are “letters” as far as Java is concerned, you can use the isJavaIdentifierStart and isJavaIdentifierPart methods in the Character class to check.

If you are really curious as to what Unicode characters are “letters” as far as Java is concerned, you can use the isJavaIdentifierStart and isJavaIdentifierPart methods in the Character class to check.

You also cannot use a Java reserved word for a variable name. (See Appendix I for a list of reserved words.)

You can have multiple declarations on a single line

int i, j; // both are integers

However, we don't recommend this style. If you define each variable separately, your programs are easier to read.

As you saw, names are case-sensitive, for example hireday and hireDay are two separate names. In general, you should not have two names that only differ in their letter case. However, sometimes it is difficult to come up with a good name for a variable. Many programmers then give the variable the same name of the type, such as

Box box; // ok--Box is the type and box is the variable name

However, a better solution is to use an “a” prefix for the variable:

Box aBox;

As you saw, names are case-sensitive, for example hireday and hireDay are two separate names. In general, you should not have two names that only differ in their letter case. However, sometimes it is difficult to come up with a good name for a variable. Many programmers then give the variable the same name of the type, such as

Box box; // ok--Box is the type and box is the variable name

However, a better solution is to use an “a” prefix for the variable:

Box aBox;
  • + Share This
  • 🔖 Save To Your Account