Java Identifiers
Identifiers are names given to elements in your program such as variables, classes, methods, and interfaces. Proper naming conventions and rules should be followed when creating identifiers.
Key Topics
1. Naming Rules
Rules that must be followed when naming identifiers:
- Identifiers can start with a letter, underscore
_
, or dollar sign$
. - After the first character, identifiers can have any combination of letters, digits, underscores, or dollar signs.
- Identifiers are case-sensitive (
myVar
andmyvar
are different). - Cannot use Java reserved keywords (e.g.,
class
,public
).
Example
public class IdentifierRules {
public static void main(String[] args) {
int _value = 10;
int $amount = 20;
int totalAmount = _value + $amount;
System.out.println("Total Amount: " + totalAmount);
}
}
Output:
Total Amount: 30
2. Naming Conventions
Best practices for naming identifiers:
- Variables and Methods: Use camelCase (e.g.,
myVariable
,calculateTotal
). - Classes and Interfaces: Start with a capital letter and use PascalCase (e.g.,
MyClass
,Runnable
). - Constants: Use all uppercase letters with underscores (e.g.,
MAX_VALUE
).
Example
public class NamingConventions {
// Constants
public static final int MAX_VALUE = 100;
// Variables
private int myVariable;
// Methods
public void calculateTotal() {
int total = MAX_VALUE + myVariable;
System.out.println("Total: " + total);
}
public static void main(String[] args) {
NamingConventions example = new NamingConventions();
example.myVariable = 50;
example.calculateTotal();
}
}
Output:
Total: 150
Key Takeaways
- Follow Java's naming rules to avoid compilation errors.
- Use naming conventions to make your code more readable and maintainable.
- Avoid using reserved keywords as identifiers.