Java Keywords & Identifiers
Keywords
Keywords like class, int, if, and return are reserved by the language itself and have fixed meaning to the compiler, so trying to name a variable int or class will fail to compile.
Example: Keywords
public class Main {
public static void main(String[] args) {
// int int = 5; // ILLEGAL - 'int' is a reserved keyword, not a valid identifier
int total = 5;
System.out.println(total);
}
}
Login to try C/C++/Java/PHP code in the editor
Identifiers
An identifier is any name you choose for a variable, method, class, or package -- picking clear, descriptive identifiers (like totalPrice instead of x) makes your code self-explanatory without extra comments.
Example: Identifiers
public class Main {
public static void main(String[] args) {
int totalPrice = 250; // clear identifier instead of 'x'
System.out.println(totalPrice);
}
}
Login to try C/C++/Java/PHP code in the editor
Naming Rules
Java requires identifiers to start with a letter, underscore, or dollar sign, and forbids spaces or symbols like # or - anywhere in the name -- numbers are allowed, but never as the very first character.
Example: Naming Rules
public class Main {
public static void main(String[] args) {
int _count = 1;
int $price = 2;
int total2 = 3;
// int 2total = 4; // ILLEGAL - cannot start with a digit
System.out.println(_count + $price + total2);
}
}
Login to try C/C++/Java/PHP code in the editor
Case Sensitivity in Names
Because page and Page are treated as completely different identifiers, mixing up capitalization when referencing a variable is a very common source of 'cannot find symbol' compiler errors.
Example: Case Sensitivity in Names
public class Main {
public static void main(String[] args) {
String page = "lowercase";
String Page = "uppercase";
System.out.println(page + " is not the same identifier as " + Page);
}
}
Login to try C/C++/Java/PHP code in the editor
Best Practices for Names
Favor full words over abbreviations for anything beyond a loop counter -- customerCount over cc -- since future readers (including you, months later) will spend far less time decoding what the variable holds.
Example: Best Practices for Names
public class Main {
public static void main(String[] args) {
int customerCount = 42; // clearer than 'cc'
System.out.println(customerCount);
}
}
Login to try C/C++/Java/PHP code in the editor
Chapter Quiz — Complete all 12 topics to unlock
0/12 topics done
Complete these topics first: