C

Core Java tutorial for beginners

Clean • Professional

Java Keywords & Identifiers – Rules, Examples & Best Practices (Java Tutorial)

3 minute

Java Keywords & Identifiers

This guide explains what keywords and identifiers are in Java, their rules, best practices, and examples. It’s beginner-friendly, interview-ready, and optimized for Google ranking.


What Are Keywords in Java?

  • Keywords are reserved words in Java that have a special meaning in the language.
  • You cannot use keywords as names for variables, classes, methods, or identifiers.
  • Java has 52 keywords (depending on version) and 5 reserved literals like true, false, null.

List of Java Keywords (Java 17)

KeywordKeywordKeywordKeyword
abstractassertbooleanbreak
bytecasecatchchar
classconst*continuedefault
dodoubleelseenum
extendsfinalfinallyfloat
forgoto*ifimplements
importinstanceofintinterface
longnativenewpackage
privateprotectedpublicreturn
shortstaticstrictfpsuper
switchsynchronizedthisthrow
throwstransienttryvoid
volatilewhileyieldrecord
sealedpermitsnon-sealedvar
moduleopenrequiresexports

⚠️ const and goto are reserved but not used in Java.


What Are Identifiers in Java?

  • Identifiers are names you give to classes, methods, variables, and other elements in Java.
  • They help uniquely identify these program elements in your code.

Rules for Identifiers

  1. Must start with a letter, $, or _.
  2. Can contain letters, digits, $, or _.
  3. Cannot be a keyword.
  4. Java is case-sensitive (ageAge).
  5. No spaces or special characters allowed.

Valid & Invalid Identifiers Examples

Valid IdentifiersInvalid Identifiers
int age;int 2age; // starts with digit
String studentName;String student-name; // invalid char
double _salary;int class; // keyword

Naming Conventions (Best Practices)

ElementConventionExample
ClassPascalCaseStudentDetails
MethodcamelCasecalculateSalary()
VariablecamelCasetotalSalary
ConstantUPPERCASEMAX_AGE
Packagelowercasecom.example.project

Following conventions improves readability, collaboration, and maintainability.


Example Program Using Keywords & Identifiers

public class Student {

    // Instance Variables (Identifiers)
    String studentName;
    int age;
    final double PI = 3.14159; // Constant

    // Method
    public void displayInfo() {
        System.out.println("Name: " + studentName);
        System.out.println("Age: " + age);
        System.out.println("PI Value: " + PI);
    }

    public static void main(String[] args) {
        Student s1 = new Student();
        s1.studentName = "John";
        s1.age = 25;
        s1.displayInfo();
    }
}

Output:

Name: John
Age: 25
PI Value: 3.14159

 

Article 0 of 0