Java Variable Identifiers
In Java, all variables must have a unique name called an identifier and comprised of at least a single character.
Java has both rules as well as conventions for variable naming.
Rules establish what names can and cannot be used, while conventions are used to make the lives of programmers easier.
Variable Identifier Rules
The following rules govern identifiers in Java:
- Alphanumeric characters ([A-Z],[a-z],[0-9]), underscores ‘_‘, and dollar signs ‘$‘ can all be used.
- Names are case sensitive. ‘myInt’ and ‘myint’ will be treated as unique variables.
- Reserved words cannot be used.
- An identifier cannot contain white space.
Variable Identifier Conventions
In addition to the above rules, there are also several conventions that are used to make developers’ lives easier.
There are a lot of benefits to following these conventions, and it’s a good idea to stick to them. They help improve code readability and establishes consistent patterns between code written by different people.
- Variable names should begin with a lowercase letter (not an uppercase letter, underscore, or dollar sign).
- Variables should have descriptive names that improve code readability.
- The optimum variable name length is between 4-15 characters.
- One-character names should be avoided except for temporary ‘throwaway’ variables. Oracle specifies that common one-character names for temporary variables are ‘i’, ‘j’, ‘k’, ‘m’, and ‘n’.
- Although not specified by Oracle, it is common to use camelCase when naming variables. When a variable identifier has more than one word, leave the first letter of the first word in lowercase and then capitalize the first letter of all other words.
Examples of Variable Identifiers
The following examples are allowed and follow naming conventions:
- index
- indexNumber
- firstName
- clientId
Note that these are all descriptive and use camelCase.
The following examples are allowed but not recommended because they don’t follow convention:
- $id
- Variables should start with a lowercase letter, not a dollar sign.
- LastName
- Variables should use camelCase. UpperCamelCase is more commonly used for classes, interfaces, enums, and annotations.
- a
- Variable names should be descriptive. The name ‘a’ doesn’t tell us anything about what it’s used for.
- iReallyReallyLikeJavaProgramming
- This name is unnecessarily long. It’s also unclear what this would actually be used for.
The following examples are not allowed at all because they break the rules for valid identifiers:
- %myName
- It is not allowed to start an identifier with the percent ‘%’ character.
- int
- ‘int’ is a reserved keyword and thus cannot be used as a valid identifier.
- my Var
- This example contains a white space and is therefore invalid. ‘myVar’ would be fine, although again not particularly descriptive.