All the Java components classes, variables, and methods need names. These names are called identifier. Legal identifiers must be composed of only Unicode characters, numbers, currency symbols, and connecting characters (such as underscores).
- Identifiers are case-sensitive. x and X are two different identifiers.
- You can’t use a Java keyword as an identifier.
- Identifiers must start with a letter, a currency character ($), or a connecting character such as the underscore (_). Identifiers cannot start with a digit.
- After the first character, identifiers can contain any combination of letters, currency characters, connecting characters, or numbers.
- There is no limit to the number of characters an identifier can contain.
Few examples of legal identifiers:
int _x;
int $x;
int x2c;
int this_is_a_valid_identifier;
Few examples of illegal identifiers:
int .x;
int x.c;
int x&;
int x-c;
int 9x;
Java code conventions
There are few naming conventions for variables, classes and methods. Following are the recommended conventions:
- Conventions for Classes and interfaces: Class names should be of nouns by convention like Student, Employee, Automobile, String etc. Interface names should be adjectives by convention like Runnable, Serializable etc. The first letter of the Class and Interface should be a capital letter. If there are several words in a Class name, the first letter of inner words should be upper case. This type of format is commonly called as “CamelCase”.
- Convention for variables: Variable names should be meaningful like simpleInterest, rate, year etc. Variables should start with lowercase and follow CamelCase.
- Convention for methods: Method names are typically verb-noun pairs, start with a lowercase and follow CamelCase. For example, getResult, setResult, calculateInterest etc.
- Convention for constants: Constants are created by using uppercase letters separated by underscore. For example, HEIGHT, MIN_AGE, MAX_AGE etc.
Java keywords
Following is the list of Java keywords:
abstract | assert | boolean | break | byte | case |
catch | char | class | const | continue | default |
do | double | else | enum | extends | final |
finally | float | for | goto | if | implements |
import | instanceof | int | interface | long | native |
new | package | private | protected | public | return |
short | static | strictfp | super | switch | synchronized |
this | throw | throws | transient | try | void |
volatile | while |