Core Java Fundamentals ยท Java Basics
Learn the rules for naming variables, methods, and classes in Java, and understand the role of reserved words.
public class IdentifierDemo {
public static void main(String[] args) {
// --- VALID IDENTIFIERS ---
int age = 25;
double _salary = 50000.50;
String $name = "Alex";
int userCounter1 = 10;
// Java is case-sensitive
int Age = 30; // 'Age' is different from 'age'
// --- INVALID IDENTIFIERS (examples commented out) ---
// int 1stPlace; // Cannot start with a digit
// String my-name; // Hyphens are not allowed
// double final; // 'final' is a keyword
// boolean true; // 'true' is a reserved literal
System.out.println("Name: " + $name);
System.out.println("Age: " + age);
System.out.println("Another Age: " + Age);
}
}public and class are keywords.age is a valid identifier. It starts with a letter. int is a keyword._salary is a valid identifier.String is a pre-defined class identifier.userCounter1 is a valid identifier.Age is completely different from the variable age declared earlier.1stPlace is invalid because an identifier cannot begin with a number.my-name is invalid because special characters like hyphens (-) are not allowed. Only letters, digits, underscores, and dollar signs are permitted.final is a keyword, so it cannot be used as an identifier.true, false, and null also cannot be used as identifiers.