Keywords

Keywords are reserved words in Java that have predefined meanings and cannot be used as identifiers (like variable names, class names, or method names). These words are part of the Java syntax, and each has a specific function within the language. Java keywords are case-sensitive.

 

Examples of Keywords

  • Data types: int, double, float, char, boolean
  • Control flow: if, else, switch, case, for, while, do, break, continue
  • Access modifiers: public, private, protected
  • Class-related: class, interface, extends, implements
  • Object-related: new, this, super
  • Exception handling: try, catch, finally, throw, throws
  • Miscellaneous: static, final, abstract, synchronized, volatile, native, return, void

Java has 50 reserved keywords, and none of these can be used as an identifier.

 

Identifiers in Java

Identifiers are names used to identify variables, methods, classes, objects, packages, or interfaces. These names are user-defined, and they follow specific rules in Java.

Rules for Identifiers

  • Valid Characters: Identifiers can only contain letters (A-Z, a-z), digits (0-9), underscore (_), and dollar sign ($).
  • Cannot Start with a Digit: Identifiers must start with a letter, underscore, or dollar sign, but not a digit.
    • Valid: myVariable, _myVariable, $myVariable
    • Invalid: 1stVariable
  • Case-sensitive: Java identifiers are case-sensitive, meaning myVariable and MyVariable are different.
  • Cannot be a Keyword: You cannot use Java keywords as identifiers.
  • No Limit on Length: Identifiers can be of any length, though it’s recommended to keep them concise and descriptive.

 

Best Practices for Identifiers

  • Use meaningful names that describe the purpose of the variable, class, or method.
  • Follow camelCase for variable and method names (myVariable, calculateSum).
  • Use PascalCase for class names (MyClass, EmployeeDetails).
  • Avoid single-letter names unless they are used in short loops (e.g., i, j).
Last updated on