JavaBasic syntax and simple programsCode style

Naming variables

16 seconds read

Why is naming important?

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. Experienced programmers put a lot of care much into naming to make their programs easy to understand. It is important because programmers spend a lot of time on reading and understanding code written by other programmers. If variables have bad names, even your own code will seem unclear to you in a few months.

So, try to always 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 (class, static, int are illegal names).

Based on these rules, you may conclude that whitespaces are not allowed in the name of a variable.

It is important that you do not break these rules; otherwise, your program will not work.

Here are some valid names of variables:

number, $ident, bigValue, _val, abc, k, var

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 and __ (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: number, price);
  • 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: numberOfCoins);
  • variable names should not start with _ and $ characters, although they are allowed;
  • choose a name that makes sense, e.g. score makes 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.
6 learners liked this piece of theory. 0 didn't like it. What about you?
Report a typo