AP Computer Science Java: Lesson 1.3a
Variables and Constants - Java Identifiers


Lesson 1.3a - Java Identifiers
Purpose: To learn the rules and conventions for Java identifiers

Identifiers
An identifier is a programmer-defined name for something in Java such as a variable, a class or a method. There are several rules and conventions for names in Java. A rule means that it is a requirement of Java. A convention is a generally accepted way of doing something. It is not a requirement, but rather a good idea. It ensures that all programmers use the same style. That makes it easier for programmers to collaborate.

Identifier Naming Rules
1. Must begin with a letter ('a'..'z', 'A'..'Z')
2. All other characters must be a letter, number or an underscore(_)
3. May not contain any spaces (stateTax not state Tax)
4. Cannot be the same as an already reserved Java keyword, such as public or if
* Note: Java is a case-sensitive language. That means it treats lowercase and uppercase letters as different letters. So when you name a variable, you must type it the same way every time so that it is recognized as the same variable. For example, the identifier number is different from Number.

Identifier Naming Conventions
1. Classes begin with a capital letter, lowercase after except for beginnings of secondary words in the variable (IntNum, not Intnum)
2. Variables and methods begin with lowercase letters, capitalizing secondary words in the name (stateTax, not statetax)
3. Constants are all capital letters with underscores separating words (TAX_RATE not TAXRATE)

Examples
num1
legal name - lowercase implies that it is a variable or method
Num1
another legal name - uppercase implies that it is a class
NUMBER
yet another legal name - all caps implies it is a constant
lownum
legal, but not preferred - multiple words should be camelCase
low_num
better, but should be camelcase
lowNum
perfect
low num
ILLEGAL - contains a space
3rdBase
ILLEGAL - begins with a number
import
ILLEGAL - name is already used as a Java keyword

 

© DanShuster.com