Java Identifiers

What are Identifiers?

Identifiers are unique names given to Java variables. They help in identifying variables in your code. Identifiers can range from simple names (like x or y) to more descriptive names (such as age, sum, or totalVolume).



Using descriptive names is recommended as it makes your code easier to understand and maintain.

Example:

// Descriptive name
int secondsPerMinute = 60;

// Less clear name
int s = 60;

In the example above, secondsPerMinute is a more descriptive and understandable name compared to s.




Rules for Naming Variables

Here are the general rules for naming variables in Java:

  1. Allowed Characters: Names can contain letters, digits, underscores (_), and dollar signs ($).
  2. Starting Character: Names must begin with a letter.
  3. Lowercase Start: Names should start with a lowercase letter and cannot contain whitespace.
  4. Special Characters: Names can also begin with a dollar sign ($) or an underscore (_).
  5. Case Sensitivity: Names are case-sensitive, meaning myVar and myvar are considered different variables.
  6. No Reserved Words: Reserved words (like Java keywords such as int or boolean) cannot be used as names.




Examples

Let’s look at some examples to understand these rules better:

// Correct usage
int age = 25;
int totalAmount = 100;
int $dollarSign = 5;
int _underscore = 10;
System.out.println(age + totalAmount + $dollarSign + _underscore);

// Incorrect usage
// int 1age = 25; // Cannot start with a digit
// int total Amount = 100; // Cannot contain whitespace
// int int = 5; // Cannot use reserved words

In the above examples, age, totalAmount, $dollarSign, and _underscore are all valid identifiers. Examples commented out show incorrect usages according to the rules mentioned.

Scroll to Top