As you may know, every variable has a name that uniquely identifies it among other variables. Giving a good name to a variable may not be as simple as it seems. This topic will teach you how to name variables in Java properly.
Why is naming important?
Experienced programmers put a lot of care into naming to make their programs easy to understand. It is important because programmers spend a lot of their time getting through the code written by other programmers. If variables have bad names, even your own code will seem unclear to you in a few months.
Always try to give descriptive and concise names to all variables. As a result, any programmer will enjoy your code for a long time.
In addition, there are two sets of rules that restrict the possible names for variables.
Rules for naming variables
Java has some rules for naming variables:
- names are case-sensitive;
- a name can include Unicode letters, digits, and two special characters (
- a name cannot start with a digit;
- a name must not be a keyword (
int, etc. are illegal names).
Based on these rules, you may conclude that whitespaces are not allowed in the name of a variable.
It is important not to break these rules; otherwise, the program will not work.
Here are some valid names of variables:
number, $ident, bigValue, _val, abc, k, var
Note that to keep backward compatibility the word
var can be used as a variable name even after Java 10 was released.
And here are some invalid ones:
@ab, 1c, !ab, class
Since Java 9 the single character
_ is an invalid name for a variable, but
__ (a double
_ ) are legal names.
Naming conventions for variables
Also, there are the following conventions for naming variables:
- if a variable name is a single word it should be in lowercase (for instance:
- if a variable name includes multiple words it should be in
lowerCamelCase, i.e. the first word should be in lowercase and each word after the first should have its first letter written in uppercase (for instance:
- variable names should not start with
$characters, although they are allowed;
- choose a name that makes sense, e.g.
scoremakes more sense than
s, although they are both valid.
These conventions are optional, but it is strongly recommended to follow them. As we mentioned at the beginning of this lesson, they make your code more readable for you and other Java programmers.