Java Keywords and Identifiers


In Java, as in any programming language, proper naming conventions and understanding reserved words are essential for writing clean, understandable, and functional code. Java provides a set of keywords, which are reserved words with predefined meanings, and identifiers, which are names used to identify variables, methods, classes, and other elements in your code.


What Are Java Keywords?

Keywords are reserved words that have a predefined meaning in the Java programming language. These words cannot be used as names for variables, methods, or any other identifiers. Keywords are an essential part of Java syntax and define the structure of the language.

List of Java Keywords

Java has a set of 50 reserved keywords that are used to define the language's syntax. Below is the list of all Java keywords:

  1. abstract
  2. assert
  3. boolean
  4. break
  5. byte
  6. case
  7. catch
  8. char
  9. class
  10. const (Not used)
  11. continue
  12. default
  13. do
  14. double
  15. else
  16. enum
  17. extends
  18. final
  19. finally
  20. float
  21. for
  22. goto (Not used)
  23. if
  24. implements
  25. import
  26. instanceof
  27. int
  28. interface
  29. long
  30. native
  31. new
  32. null
  33. package
  34. private
  35. protected
  36. public
  37. return
  38. short
  39. static
  40. strictfp
  41. super
  42. switch
  43. synchronized
  44. this
  45. throw
  46. throws
  47. transient
  48. try
  49. void
  50. volatile

Important Points About Keywords:

  • Reserved Words: Keywords are predefined by Java and cannot be used as identifiers.
  • Case-sensitive: Java keywords are case-sensitive, meaning int and Int are different.
  • Contextual Use: Keywords perform specific actions based on their context in the code.

What Are Java Identifiers?

An identifier is a name used to identify a variable, method, class, interface, or other elements in your program. Unlike keywords, identifiers are not predefined and can be chosen by the programmer, as long as they follow Java's naming conventions.

Rules for Naming Identifiers:

  1. Start with a Letter, Dollar Sign ($), or Underscore (_): Identifiers must start with a letter (a-z, A-Z), a dollar sign ($), or an underscore (_).

    • Valid: variableName, _value, $data
    • Invalid: 123value (cannot start with a number)
  2. Subsequent Characters: After the first character, an identifier can contain letters, digits (0-9), dollar signs ($), or underscores (_).

    • Valid: value1, sum_of_values, var$
  3. No Reserved Keywords: Identifiers cannot be Java keywords. For example, int, class, and return cannot be used as identifiers.

  4. No Length Limit: Java does not limit the length of an identifier, but it's a good practice to keep them meaningful and readable.

  5. Case Sensitivity: Java is case-sensitive, so myVariable, myvariable, and MYVARIABLE are considered different identifiers.

Examples of Valid and Invalid Identifiers:

  • Valid Identifiers:

    int age = 25;
    String studentName = "John";
    double $price = 50.5;
    float _percentage = 85.0f;
    
  • Invalid Identifiers:

    int 1stPlace = 1;  // Starts with a number
    String public = "keyword";  // 'public' is a reserved keyword
    

How Java Identifiers are Used

Identifiers are used to name variables, methods, classes, interfaces, packages, and other user-defined elements in Java. Here are some examples of how you would use identifiers in Java:

Example 1: Using Identifiers for Variables

public class Student {
    // Declare variables (identifiers)
    String studentName = "Alice";
    int studentAge = 21;
    
    // Method to display student details
    public void displayInfo() {
        System.out.println("Name: " + studentName);
        System.out.println("Age: " + studentAge);
    }
    
    public static void main(String[] args) {
        Student student = new Student();
        student.displayInfo();  // Calling method using an identifier
    }
}

Example 2: Using Identifiers for Methods

public class Calculator {
    // Method identifier
    public int add(int a, int b) {
        return a + b;
    }
    
    public static void main(String[] args) {
        Calculator calc = new Calculator();
        System.out.println("Sum: " + calc.add(5, 3));  // Calling method with identifier
    }
}

Example 3: Using Identifiers for Classes

// Class identifier
public class Vehicle {
    private String model;
    
    public Vehicle(String model) {
        this.model = model;
    }

    public void displayModel() {
        System.out.println("Vehicle Model: " + model);
    }

    public static void main(String[] args) {
        Vehicle vehicle = new Vehicle("Toyota");
        vehicle.displayModel();  // Accessing class method using identifier
    }
}

Best Practices for Naming Identifiers

Choosing meaningful and readable identifiers is crucial for maintaining code quality and readability. Here are some best practices:

  1. Use Descriptive Names: Always give variables and methods names that describe their purpose. For instance, use studentName instead of x or s, and calculateTotalPrice() instead of doStuff().

  2. Follow Naming Conventions:

    • Variables: Use camelCase notation, starting with a lowercase letter (e.g., totalPrice, studentName).
    • Classes and Interfaces: Use PascalCase notation, starting with an uppercase letter (e.g., CarModel, StudentDetails).
    • Constants: Use UPPERCASE with underscores to separate words (e.g., MAX_VALUE, PI).
  3. Avoid Single Character Names: Except for loop variables like i, j, or k, avoid using single characters for variable names. This makes the code harder to understand.

  4. Avoid Using Java Keywords as Identifiers: Never use reserved keywords like class, int, public, etc., as identifiers.

  5. Be Consistent: Stick to a consistent naming pattern throughout your codebase for clarity and maintainability.