JAVA VARIABLES

Java variable names

The name of a variable, method, class or other program element is called an identifier. A well-chosen identifier follows Java syntax and clearly communicates the element’s purpose.

What is an identifier?

Every variable needs a name so you can refer to it in code. The name must be unique within the scope where the variable is defined. Different parts of a program can have variables with the same name if their scopes do not overlap.

Short names such as x or yare valid. However, in longer code, a descriptive name such as userAge or totalVolumemakes the purpose of the stored value easier to understand.

Choose meaningful names

Both variables in the example are valid, but the first name provides more information:

// A clear name
int minutesPerHour = 60;

// A valid but unclear name
int m = 60;

Name minutesPerHour explains the value without requiring an extra comment. m may suit a very small formula, but its purpose is unclear in a wider context.

Java identifier rules

  • A name may contain letters, digits, an underscore _ and the dollar sign $.
  • A name cannot start with a digit.
  • A name cannot contain spaces.
  • Java is case-sensitive.
  • Java keywords such as int, boolean or classcannot be used.
  • A single underscore _ has been reserved since Java 9 and cannot be an identifier.
int age = 20;
int totalScore = 150;
int item2 = 7;
int _temporaryValue = 3;
int $generatedValue = 9;
$ and _ are allowed at the beginning, but are rarely used.

For ordinary program variables, starting the name with a lowercase letter is clearest.

Uppercase and lowercase letters differ

The identifiers userAge and userage are not the same name in Java. This example therefore creates two different variables:

int userAge = 20;
int userage = 35;

System.out.println(userAge); // 20
System.out.println(userage); // 35

Consistent capitalisation reduces mistakes and makes elements’ purposes easier to recognise.

Invalid identifiers

These declarations break Java’s rules and would cause compiler errors:

// Cannot start with a digit
int 2ndNumber = 5;

// Cannot contain a space
int my age = 20;

// Cannot use a Java keyword
int int = 10;
  1. 2ndNumber starts with a digit.
  2. my age contains a space, so Java reads it as separate tokens.
  3. int is a reserved Java keyword.

The camelCase convention

Java variable and method names usually use camelCase style: the first word starts with a lowercase letter, and each subsequent word starts with an uppercase letter. Spaces and hyphens are not used.

String firstName = "Ieva";
int completedTasks = 12;
boolean hasActiveSubscription = true;

This is not a compiler requirement, but it is a convention throughout the Java ecosystem. Following it makes code easier for other developers to read.