Java Notes
Complete guide to Java identifiers — naming rules, conventions, valid vs invalid names, best practices for naming classes, methods, variables, and constants.
An identifier is a name given to a class, method, variable, package, constant, or any other user-defined item in Java. Choosing good identifiers makes your code readable and maintainable.
What Are Identifiers?
// Every name you create in Java is an identifier:
package com.wohotech.demo; // "com", "wohotech", "demo" are identifiers
public class StudentManager { // "StudentManager" is an identifier
private String firstName; // "firstName" is an identifier
static final int MAX = 100; // "MAX" is an identifier
public void calculateGPA(double[] grades) { // "calculateGPA", "grades"
double total = 0; // "total" is an identifier
for (double g : grades) { // "g" is an identifier
total += g;
}
}
}Rules for Identifiers (Compiler-Enforced)
These are hard rules — violating them causes compilation errors:
public class IdentifierRules {
public static void main(String[] args) {
// RULE 1: Can contain letters, digits, underscore (_), and dollar sign ($)
int age = 25; // ✅ letters
int age2 = 30; // ✅ letters + digits
int _count = 0; // ✅ underscore
int $price = 99; // ✅ dollar sign
int my_variable = 1; // ✅ mix
// RULE 2: Cannot START with a digit
// int 2name = 5; // ❌ COMPILE ERROR
// int 123abc = 5; // ❌ COMPILE ERROR
int name2 = 5; // ✅ digit not at start
// RULE 3: Cannot be a Java keyword
// int class = 5; // ❌ 'class' is a keyword
// String for = "x"; // ❌ 'for' is a keyword
// int null = 0; // ❌ 'null' is reserved
int Class = 5; // ✅ different case (but bad practice!)
// RULE 4: Cannot contain spaces or special characters
// int my variable = 5; // ❌ space
// int my-var = 5; // ❌ hyphen
// int my+var = 5; // ❌ plus sign
// int my.var = 5; // ❌ dot (used for member access)
// RULE 5: No length limit (but be reasonable)
int thisIsAVeryLongVariableNameButItIsStillValid = 42; // ✅ but too long!
// RULE 6: Case-sensitive
int number = 1;
int Number = 2;
int NUMBER = 3;
// These are THREE different variables!
System.out.println(number + ", " + Number + ", " + NUMBER);
// RULE 7: Unicode characters are allowed
int café = 1; // ✅ accented characters
int 数量 = 5; // ✅ Chinese characters
int αβγ = 3; // ✅ Greek letters
}
}1, 2, 3
Naming Conventions (Community Standards)
These are conventions (not compiler-enforced) that all Java developers follow:
// 1. CLASSES & INTERFACES: PascalCase (each word capitalized)
public class StudentManager { }
public class LinkedHashMap { }
public interface Serializable { }
public interface ActionListener { }
// 2. METHODS: camelCase (first word lowercase, then capitalize)
public void calculateTotalPrice() { }
public String getFirstName() { }
public boolean isActive() { } // boolean: "is" prefix
public boolean hasPermission() { } // boolean: "has" prefix
// 3. VARIABLES: camelCase (same as methods)
int studentAge;
String firstName;
double accountBalance;
boolean isLoggedIn;
// 4. CONSTANTS: ALL_UPPER_CASE with underscores
static final int MAX_RETRY_COUNT = 3;
static final String DATABASE_URL = "localhost:5432";
static final double TAX_RATE = 0.08;
// 5. PACKAGES: all lowercase, reverse domain
package com.wohotech.javacourse.fundamentals;
package org.apache.commons.lang3;
// 6. ENUM VALUES: ALL_UPPER_CASE
enum Status { ACTIVE, INACTIVE, PENDING, DELETED }
enum HttpMethod { GET, POST, PUT, DELETE, PATCH }
// 7. TYPE PARAMETERS: Single uppercase letter
class Box<T> { } // T = Type
interface List<E> { } // E = Element
class Map<K, V> { } // K = Key, V = ValueGood vs Bad Identifier Names
public class NamingExamples {
// ❌ BAD — too short, meaningless
int x, y, z;
int a1, a2, a3;
String s, str;
// ✅ GOOD — descriptive, self-documenting
int studentAge;
int totalOrderCount;
String customerEmail;
// ❌ BAD — misleading or confusing
int data; // what data?
String info; // what info?
boolean flag; // what flag?
int temp; // temporary what?
// ✅ GOOD — reveals purpose
int remainingAttempts;
String errorMessage;
boolean isConnectionActive;
int currentPageIndex;
// ❌ BAD — hungarian notation (outdated)
int iCount;
String strName;
boolean bActive;
// ✅ GOOD — modern style
int count;
String name;
boolean active;
// ❌ BAD — abbreviations and acronyms
int numStdnts;
String usrNm;
int calcTtl;
// ✅ GOOD — full words
int numberOfStudents;
String username; // well-known abbreviation is OK
int calculatedTotal;
public static void main(String[] args) {
System.out.println("Good names make code self-documenting!");
}
}Good names make code self-documenting!
Practical Naming Guidelines
public class PracticalNaming {
// Boolean variables: use is/has/can/should prefix
private boolean isValid;
private boolean hasChildren;
private boolean canProceed;
private boolean shouldRetry;
// Collections: use plural nouns
private List<String> studentNames; // not studentNameList
private Map<String, Integer> wordCounts; // not wordCountMap
private Set<Integer> uniqueIds;
// Methods that return boolean: use is/has/can/should
public boolean isEmpty() { return true; }
public boolean hasNext() { return false; }
public boolean canExecute() { return true; }
// Getter/Setter convention
private String name;
public String getName() { return name; }
public void setName(String name) { this.name = name; }
// Factory methods: use create/of/from/valueOf
public static PracticalNaming create() { return new PracticalNaming(); }
public static PracticalNaming fromJson(String json) { return new PracticalNaming(); }
// Conversion methods: use toXxx
public String toString() { return "PracticalNaming"; }
public int toInteger() { return 0; }
public static void main(String[] args) {
System.out.println("Follow conventions consistently!");
}
}Follow conventions consistently!
Valid vs Invalid Identifiers — Quick Test
| Identifier | Valid? | Reason |
|---|---|---|
myVariable | ✅ | Standard camelCase |
_temp | ✅ | Starts with underscore |
$total | ✅ | Starts with dollar |
student2 | ✅ | Digit not at start |
2student | ❌ | Starts with digit |
my-var | ❌ | Hyphen not allowed |
my var | ❌ | Space not allowed |
class | ❌ | Reserved keyword |
Class | ✅ | Different case (but bad practice) |
public | ❌ | Reserved keyword |
_ | ❌ | Reserved since Java 9 |
var | ✅ | Contextual keyword (can be identifier) |
πRadius | ✅ | Unicode allowed |
MAX_SIZE | ✅ | Constant convention |
Common Mistakes
- Using single-letter names outside loops —
x,n,sare only acceptable as loop counters (i,j,k) or lambda parameters. Otherwise, use descriptive names. - Starting with uppercase for variables —
String Name = "Alice";looks like a class name. Variables use camelCase:String name = "Alice";. - Using
_alone as an identifier — since Java 9, the single underscore_is reserved and cannot be used as a variable name. - Inconsistent naming across a project — if you use
userIdin one class anduser_idin another, it creates confusion. Pick one style and stick with it. - Names that differ only in case — having
countandCountin the same scope is legal but extremely confusing.
Interview Questions
Q1: What are the rules for naming identifiers in Java?
Answer: (1) Can contain letters, digits, underscore, and dollar sign. (2) Cannot start with a digit. (3) Cannot be a Java keyword or reserved word. (4) Cannot contain spaces or special characters. (5) Case-sensitive. (6) No length limit. Additionally, Unicode characters are allowed, making international names valid.
Q2: What are Java naming conventions?
Answer: Classes use PascalCase (StudentManager), methods and variables use camelCase (calculateTotal), constants use UPPER_SNAKE_CASE (MAX_VALUE), packages use all lowercase (com.example.app). Boolean variables typically start with is, has, or can.
Q3: Are name, Name, and NAME the same identifier?
Answer: No. Java is case-sensitive, so these are three completely different identifiers. By convention, name would be a variable, Name would look like a class (poor practice for a variable), and NAME would be a constant.
Q4: Can you use var as a variable name?
Answer: Yes! var is a contextual keyword (Java 10+) — it acts as a keyword only in local variable declarations with initializers. In all other positions, it's a regular identifier. So int var = 5; is valid Java.
Q5: Why can't identifiers start with a digit?
Answer: This is a language design choice that prevents ambiguity in parsing. If 123abc were valid, the compiler couldn't tell if it's the number 123 followed by identifier abc, or a single identifier 123abc. By requiring identifiers to start with a non-digit, the lexer can easily distinguish numbers from names.
Summary
Identifiers are the names you give to every element in your Java program. The compiler enforces basic rules (no digits at start, no keywords, no spaces), but the community conventions (PascalCase for classes, camelCase for methods/variables, UPPER_CASE for constants) are equally important for writing professional, readable code. Good identifier names make code self-documenting and reduce the need for comments.
Exam Focus
Revise definitions, diagrams, examples, and short-answer points for Identifiers in Java.
Interview Use
Prepare one clear explanation, one practical example, and one common mistake for this Java Master Course topic.
Search Terms
java-master-course, java master course, java, master, course, fundamentals, syntax, basics
Related Java Master Course Topics