Keywords and Identifiers in Java
Introduction
In Java, keywords and identifiers play a crucial role in defining the structure and behavior of programs. Keywords have predefined meanings in the language, while identifiers are names given to elements such as variables, methods, and classes.
Keywords in Java
Keywords are reserved words in Java that have specific meanings and cannot be used for identifiers. Examples include:
- class: Used to define a class.
- public: Specifies access level as public.
- static: Denotes a method or variable that belongs to the class, not an instance.
- void: Specifies that a method does not return a value.
- if: Starts a conditional statement.
- return: Exits from a method and optionally returns a value.
Java keywords are case-sensitive and must be written in lowercase.
Identifiers in Java
Identifiers are the names used to identify variables, methods, classes, or objects. They must follow certain rules:
- Identifiers can consist of letters, digits, underscores (
_
), and dollar signs ($
). - They cannot begin with a digit.
- They cannot be the same as a Java keyword.
- Identifiers are case-sensitive.
- There is no length limit for identifiers.
Example: Keywords and Identifiers
Step 1: Write the Program
Create a file named KeywordsAndIdentifiers.java and write the following code:
public class KeywordsAndIdentifiers { // Variable identifiers int age = 25; // 'age' is an identifier String name = "Alice"; // 'name' is an identifier // Method identifier public void displayInfo() { // Keyword 'System' and 'out' System.out.println("Name: " + name); System.out.println("Age: " + age); } // Main method (entry point) public static void main(String[] args) { // Class identifier KeywordsAndIdentifiers obj = new KeywordsAndIdentifiers(); obj.displayInfo(); } }
Step 2: Compile the Program
Open the terminal or command prompt, navigate to the file location, and type:
javac KeywordsAndIdentifiers.java
Step 3: Run the Program
Type the following command to execute the program:
java KeywordsAndIdentifiers
You should see the output:
Name: Alice Age: 25
Conclusion
Keywords and identifiers are essential for writing Java programs. Understanding their rules and usage helps in creating clear and efficient code. Avoid using keywords as identifiers and follow naming conventions for better readability.