Core Java Fundamentals ยท Java Basics

Java Identifiers and Keywords

Learn the rules for naming variables, methods, and classes in Java, and understand the role of reserved words.

IdentifierDemo.java

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);
    }
}

Step by step

  1. We define a class named "IdentifierDemo". "IdentifierDemo" is an identifier. It follows the PascalCase naming convention for classes. public and class are keywords.
  2. An identifier is a name given to a variable, method, or class. Here, age is a valid identifier. It starts with a letter. int is a keyword.
  3. Identifiers can start with an underscore (_). _salary is a valid identifier.
  4. Identifiers can also start with a dollar sign ($). While allowed, it is unconventional and should be avoided in standard practice. String is a pre-defined class identifier.
  5. Identifiers can contain digits, but they cannot start with them. userCounter1 is a valid identifier.
  6. Java identifiers are case-sensitive. The variable Age is completely different from the variable age declared earlier.
  7. Now let's look at invalid identifiers. 1stPlace is invalid because an identifier cannot begin with a number.
  8. my-name is invalid because special characters like hyphens (-) are not allowed. Only letters, digits, underscores, and dollar signs are permitted.
  9. Keywords are reserved words with special meaning to the compiler. final is a keyword, so it cannot be used as an identifier.
  10. Reserved literals like true, false, and null also cannot be used as identifiers.
  11. The program finishes by printing the values of some of the validly declared variables.
  12. The program finishes by printing the values of some of the validly declared variables.
  13. The program finishes by printing the values of some of the validly declared variables.