Topic 15 of 119 2. Fundamentals of Java Programming Interactive Tutorial

Java Identifiers: Naming Rules, Conventions, and Valid Examples

14 mins read Last updated: 22 Aug 2026 17,595 views

Direct Answer & Core Concept

An identifier is the name you give to a class, variable, method, package, interface or constant in Java. For a name to be a valid identifier it must start with a letter, an underscore or a dollar sign, may then contain letters and digits, is case-sensitive, and cannot be a reserved keyword such as class or int. Java also follows naming conventions: PascalCase for classes, lowerCamelCase for variables and methods, and UPPER_SNAKE_CASE for constants.

Detailed Explanation & Mechanics

1. What Is an Identifier in Java? A Simple Definition

An identifier is simply the name you choose for the things you build in Java. When you write int totalPrice = 500; the word totalPrice is the identifier, while int is a keyword and 500 is a literal. That one line already contains all three ideas, which is why beginners often mix them up in the beginning.

Think of it the way you would think about naming a newborn. A legal name is not enough; a good name helps. totalPrice tells you what the number means, while x or d1 tells you nothing three months later. Java lets you name things fairly freely, but the language still sets a few hard rules.

Every one of these is an identifier, because you chose the name yourself:

  • A class name such as InvoiceProcessor
  • A variable name such as customerAge
  • A method name such as calculateTotal
  • A package name such as com.mycompany.billing
  • A constant name such as MAX_RETRIES

2. Where Java Identifiers Are Used

Identifiers appear in almost every position a Java programmer can write a name. Recognising them makes the rest of this topic much easier.

Where It AppearsExampleConvention
Class namepublic class InvoiceProcessorPascalCase
Interface nameinterface PaymentServicePascalCase
Enum nameenum OrderStatusPascalCase
Record namerecord CustomerAddressPascalCase
Variable namedouble accountBalancelowerCamelCase
Method namevoid applyDiscount()lowerCamelCase
Parameter nameapplyDiscount(int orderId)lowerCamelCase
Constant namestatic final int MAX_RETRIESUPPER_SNAKE_CASE
Package namepackage com.mycompany.billing;all lowercase
LabelouterLoop:lowerCamelCase

3. Identifier vs Keyword vs Literal: The Difference Beginners Miss

This is the single most common confusion at the start of Java, so it is worth nailing down early.

Architecture Diagram
DECLARING ONE VARIABLE, THREE DIFFERENT THINGS

    int  totalPrice  =  500;
     |      |          |
     |      |          +---> LITERAL   a fixed value written directly
     |      +--------------> IDENTIFIER a name YOU chose
     +---------------------> KEYWORD    a word reserved by Java

  KEYWORD    : int, class, return, if, while   (51 reserved words)
  LITERAL    : 500, 3.14, 'x', true, false, null
  IDENTIFIER : totalPrice, customerAge, calculateTotal
  • Keywords belong to the language. Java refuses to let you use them as names.
  • Literals are raw values. Writing true as a variable name is a compile error because true is the boolean literal.
  • Identifiers are your own names. If Java did not reserve the word and you typed it yourself, it is an identifier.

4. The 5 Rules for a Valid Java Identifier

Java is not fussy, but it does enforce five rules. Learn these and you can always check any name quickly.

Architecture Diagram
THE FIVE RULES AT A GLANCE

  ┌────────────────────────────────────────────────────────────┐
  │ RULE 1  The first character must be a letter, _ or $      │
  │ RULE 2  Later characters may be letters, digits, _ or $   │
  │ RULE 3  There is no practical length limit                 │
  │ RULE 4  Identifiers are case-sensitive                     │
  │ RULE 5  A keyword or literal can never be an identifier    │
  └────────────────────────────────────────────────────────────┘

          howManyItems
          _
          $total
          user2
         ┌──────┐
         │ 2nd │───►  illegal, starts with a digit
         └──────┘

Rule one allows letters from any language, not just English. Names like café, élève and even customers written in Hindi or Japanese are perfectly legal Java identifiers, provided the characters are letters rather than symbols.

Rule four catches people out constantly. totalAmount and Totalamount are two different names, and using both in one class compiles without complaint even though it is a readability disaster.

5. Valid and Invalid Identifier Examples

Memorising rules is dull. Studying real names is much faster, so here is a table of names you are likely to meet in real projects.

Name You WroteValid?Why
customerNameYesLetter first, letters only
order2YesDigit after the first character
_tempValueYesUnderscore first is legal, though discouraged
$discountYesDollar sign first is legal, though discouraged
caféYesUnicode letters are allowed
MAX_RETRIESYesUnderscores allowed after the first character
2ndPlaceNoCannot begin with a digit
my-variableNoHyphen is treated as minus
my variableNoSpaces are not allowed
customer#nameNoThe hash character is not permitted
classNoReserved keyword
returnNoReserved keyword
trueNoBoolean literal
nullNoReserved literal
_NoA lone underscore is a keyword since Java 9
Main.java
Run Online
public class ValidNames {
    public static void main(String[] args) {
        int order2 = 20;
        // fine
        int _tempValue = 5;
        // legal, but do not copy this style
        double $discount = 0.2;
        // legal, but do not copy this style
        int MAX_RETRIES = 3;
        // legal as a variable, wrong for a constant
        System.out.println(order2 + _tempValue + $discount + MAX_RETRIES);
    }
}

6. Why Certain Names Are Forbidden: Keywords and Literals

Java reserves 51 keywords. Add the three literals true, false and null, and none of those words can be a variable, class or method name.

Architecture Diagram
WORDS YOU CANNOT USE AS IDENTIFIERS

  Keywords (a small sample of the 51)
  ┌─────────────────────────────────────────────────────────┐
  │  Types      int  long  double  float  char  boolean   │
  │  Flow       if  else  for  while  switch  break       │
  │  Objects    class  new  this  super  extends           │
  │  Modifiers  public  private  protected  static  final  │
  │  Errors     try  catch  finally  throw  throws         │
  │  Reserved   const  goto  (reserved, never used)        │
  └─────────────────────────────────────────────────────────┘

  Literals (values, not names)
  ┌─────────────────────────────────────────────────────────┐
  │  true   false   null                                    │
  └─────────────────────────────────────────────────────────┘
  • The words const and goto are reserved by the specification but cannot actually appear in your code, so simply avoid them.
  • From Java 9 onwards a single underscore is treated as a keyword, which is why int _ = 5; now fails to compile.
  • Modern releases added contextual keywords such as var, record, sealed, permits and yield. They are only special in certain positions, so var can still be used as a name even though it is a poor idea.
  • Naming a variable int, or trying to redeclare the same name twice in one scope, also produces errors that look like keyword problems but are actually scope problems.

7. Java Naming Conventions: The Four Styles You Need

Validity is enforced by the compiler. Conventions are enforced by good developers, and they are the reason professional Java code looks the way it does.

StylePatternUsed ForExample
PascalCaseEvery word capitalisedClasses, interfaces, enums, recordsInvoiceProcessor
lowerCamelCaseFirst word lowercaseVariables, methods, parameterscalculateTotal()
UPPER_SNAKE_CASEAll caps with underscoresConstants declared static finalMAX_RETRY_COUNT
all lowercaseNo capitals, dot separatedPackagescom.mycompany.billing
Main.java
Run Online
HOW EACH STYLE LOOKS IN PRACTICE PascalCase InvoiceProcessor calculateInvoiceTotal lowerCamelCase invoiceProcessor calculateInvoiceTotal UPPER_SNAKE_CASE INVOICE_PROCESSOR MAX_RETRY_COUNT

The pattern itself is not what Java checks. You could name a class CalculateTotal and it would compile, but every professional Java developer reading your file would immediately know you did not follow the language's conventions.

8. Naming Classes and Interfaces

Classes are the biggest objects in your program, so give them the clearest names you can.

  • Use PascalCase, so InvoiceProcessor rather than invoiceProcessor or invoice_processor.
  • Prefer a singular noun. A class named Customer is much clearer than Customers, because one Customer object represents one customer.
  • Keep related classes in the same family: Invoice, InvoiceItem and InvoiceProcessor belong together.
  • Do not add type words such as Class or Helper to the end of a name, since InvoiceService already tells you it is a service.
  • The file name must match the public class name exactly, including capital letters, so InvoiceProcessor.java.
Main.java
Run Online
public class InvoiceProcessor {
    private int invoiceId;
    private double invoiceTotal;
    public double getInvoiceTotal() {
        return invoiceTotal;
    }
}

9. Naming Variables, Methods and Parameters

These are the names you type most often, so it pays to make them consistent.

  • Name variables with a singular, descriptive noun in lowerCamelCase, such as customerAge or accountBalance.
  • Name methods with a verb, because a method performs an action: sendEmail, calculateTotal, isValid.
  • Start boolean variables and methods with is, has, can or should, so conditions read like English sentences.
  • Keep parameters short but meaningful. Use orderId rather than o, and never reuse the same single letter for unrelated values in one method.
  • Short names are fine for obvious throwaway loops such as i, j and k, and for temporary values that disappear within a few lines.
Main.java
Run Online
public class BankAccount {
    private double accountBalance;
    // Verb + noun tells the reader what happens
    public boolean canWithdraw(double requestedAmount) {
        return requestedAmount > 0 && requestedAmount

10. Naming Constants in Java

A constant is any variable declared with both static and final. Because it never changes, its name should scream that fact.

  • Write the whole name in UPPER_SNAKE_CASE with underscores between words.
  • Use the pattern MAX_VALUE or DEFAULT_VALUE so the purpose is obvious at a glance.
  • Keep the declaration next to the top of the class so readers find it immediately.
Main.java
Run Online
CONSTANTS YOU WILL MEET IN EVERY PROJECT MAX_RETRY_COUNT DEFAULT_TIMEOUT MIN_PASSWORD_LENGTH MAX_PAGE_SIZE DEFAULT_CURRENCY TAX_RATE
Main.java
Run Online
public class Configuration {
    static final int MAX_RETRY_COUNT = 3;
    static final int DEFAULT_TIMEOUT_MS = 5000;
    static final double TAX_RATE = 0.18;
    static final String DEFAULT_CURRENCY = "INR";
}

11. Naming Packages: The Reverse Domain Trick

Java packages are written in all lowercase with dots separating the levels. The widely used pattern is to write your domain name backwards, which guarantees that names never clash across projects.

Architecture Diagram
PACKAGE NAME BUILDS FROM THE DOMAIN BACKWARDS

    mycompany.com
        |
        +--> com.mycompany.billing          billing code
                    |
                    +--> com.mycompany.billing.invoice    invoice classes
                    +--> com.mycompany.billing.payment    payment classes
  • Start with com, org, net, io or edu, which are the common top-level domains.
  • Then add your company or organisation name in lowercase, with no spaces or hyphens.
  • Add the project or module last, for example com.mycompany.billing.payment.
  • Folder structure must match the package exactly, otherwise the compiler cannot find the classes.
Main.java
Run Online
package com.mycompany.billing.invoice;
public class Invoice {
    private String invoiceId;
}

12. Why Naming Conventions Are Worth the Effort

Following conventions is not about looking fussy. It has real, practical benefits every day.

  • Beginners can read unfamiliar code because the shape of a name tells them what it is before they open the file.
  • Teams work faster because nobody has to ask what x means or which of two similar methods to call.
  • Static analysis tools, log search and refactoring features such as Rename Class rely on predictable names.
  • Interviewers read naming quality as a signal that you have written code other people had to maintain.
  • Bug reports become readable. Search for customerEmail in your logs and you immediately know which code path ran.

13. Common Identifier Mistakes Beginners Make

Nearly every Java learner makes these five mistakes at least once.

  • Using one-letter names everywhere. Your code becomes impossible to debug the moment it grows past a screen.
  • Naming variables after their type, such as int intValue or String stringValue, which repeats information the declaration already gives.
  • Adding the letter l or a capital I to names such as length or itemList, because lowercase l and number 1 look almost identical in most fonts.
  • Being consistent everywhere except one place, so a class named UserService sits next to a method called get_user_data.
  • Naming a boolean isAvailable when you actually mean available, and later writing if (available = true) by mistake, which assigns instead of comparing.

14. Java Identifier Cheat Sheet: Quick Reference

Keep this summary nearby while you write your first few programs.

You Are NamingUse This StyleGood ExampleAvoid
ClassPascalCaseInvoiceProcessorinvoice_processor
InterfacePascalCasePaymentServiceIPayment (prefix)
VariablelowerCamelCase nouncustomerAgec, a1, intValue
MethodlowerCamelCase verbcalculateTotal()doIt()
Booleanis / has / can prefixisAccountActiveaccountFlag
ConstantUPPER_SNAKE_CASEMAX_RETRIESmaxRetries
Packageall lowercasecom.mycompany.billingCom.MyCompany
Loop variableshort is finefor (int i = 0; ...)for (int counterTemp = 0; ...)

Once these eight rows become habit, move on to variables and data types, where these names finally get values to hold.

Runnable Code Example: Java Identifiers

Java 17+
Main.java
Run Online
public class IdentifierDemo {
    // Constant: UPPER_SNAKE_CASE by convention
    static final int MAX_LOGIN_ATTEMPTS = 3;
    // PascalCase for the class, which also matches the file name
    public void recordLogin(String userName, boolean isPremiumUser) {
        // Variables and parameters: lowerCamelCase
        int failedAttempts = 0;
        String accountStatus = "ACTIVE";
        double $discountRate = 0.15;
        // valid, but avoid $ in real code
        int _retryCount = 0;
        // valid, but avoid a leading underscore
        // Methods that return a boolean often read like a question
        boolean isAccountLocked = failedAttempts >= MAX_LOGIN_ATTEMPTS;
        boolean hasActiveStatus = accountStatus.equals("ACTIVE");
        System.out.println("User: " + userName);
        System.out.println("Locked: " + isAccountLocked + ", Active: " + hasActiveStatus);
        System.out.println("Discount: " + $discountRate + ", Retries: " + _retryCount);
    } public static void main(String[] args) {
        IdentifierDemo demo = new IdentifierDemo();
        demo.recordLogin("tanmoy", true);
        // Every one of these lines below is a COMPILE ERROR:
        // int 2ndPlace = 2;      // cannot start with a digit
        // int my-variable = 5;   // hyphen is not allowed
        // int my variable = 5;   // spaces are not allowed
        // int class = 4;         // class is a reserved keyword
        // boolean true = false;  // true is a literal
        // int _ = 7;             // a lone underscore is a keyword since Java 9
        // int class = 4;         // duplicate declaration in the same scope
    }
}

Common Java Technical Interview Questions & Answers

Interview Prep
Q1

What is an identifier in Java and what are the rules for creating one?

An identifier is the name assigned to a class, variable, method, package, interface or constant. A valid identifier must begin with a letter, an underscore or a dollar sign, may contain letters and digits after that, is case-sensitive, has no practical length limit, and must not be a reserved keyword.
Q2

Can a Java identifier start with a digit?

No. The first character must be a letter, an underscore or a dollar sign, so 2ndPlace is illegal while place2 is perfectly legal.
Q3

Are Java identifiers case-sensitive?

Yes. totalAmount and TotalAmount are treated as two completely different names, which means you can technically have both in the same class, although that is strongly discouraged.
Q4

Are the dollar sign and underscore allowed in identifiers?

Both are technically legal, but good practice avoids them. The dollar sign is conventionally reserved for machine-generated names, and the underscore is discouraged as a leading character because readers may treat it as a throwaway variable. A single underscore on its own became a keyword in Java 9 and is now an error.
Q5

What is the difference between a keyword, a literal and an identifier?

A keyword is a word reserved by the language such as class, int or return, so it can never be an identifier. A literal is a fixed value written directly in code such as 10, 3.14, true, false or null, which is also not a valid identifier. Anything else that you name yourself is an identifier.
Q6

Which naming convention should I follow for classes and interfaces?

Use PascalCase, meaning each word starts with a capital letter, such as InvoiceProcessor or PaymentService. The file name must also match a public class exactly, so InvoiceProcessor.java for a public class InvoiceProcessor.
Q7

How do I name a constant in Java?

Declare it as static final and write it in UPPER_SNAKE_CASE with underscores between words, for example static final int MAX_RETRY_COUNT = 5. This makes the value instantly recognisable as a constant when you read the code.
Q8

Why should identifiers be descriptive rather than short?

Code is read far more often than it is written. A name like customerBillingAddress explains its own purpose, while an abbreviation like cba forces every reader to look up a definition. Descriptive names also reduce bugs because the meaning is visible at the point of use.
Q9

Can Java identifiers contain Unicode characters?

Yes. Java allows Unicode letters, so names such as cafe, élan and even names written in Hindi or Japanese are valid identifiers, provided they are letters and not symbols or spaces.
Q10

Is there a maximum length for a Java identifier?

The specification allows extremely long names, and modern Java compilers handle names of hundreds of characters without trouble, so in practice you should name things for clarity rather than worry about length.
Q11

Why must the file name match the public class name?

Because the Java compiler looks for the public class definition inside a file whose name matches it exactly. If the names differ you get a compile error, which is why IntelliJ and Eclipse rename the file automatically when you rename a class.

Key Takeaways, Best Practices & Clean Code Rules

Java Best Practice & Production Rules

Choose names that explain themselves. A reader should be able to tell what a variable holds or what a method does without jumping to its declaration, so prefer customerBillingAddress over cba or x. Follow the standard conventions consistently: PascalCase for classes and interfaces, lowerCamelCase for variables and methods, UPPER_SNAKE_CASE for static final constants, and all-lowercase reverse-domain names for packages. Avoid the dollar sign and leading underscores, since both invite confusion in mixed-language projects. Prefix booleans with is, has, can or should so conditions read like English. If two similar names exist, such as startTime and endTime, keep that pattern everywhere instead of mixing in startDate and endingTime. Finally, rename early and often; a meaningful identifier is the cheapest documentation you will ever write.
We value your privacy & transparency

OperateTools uses cookies and local storage to ensure basic tool functionality, preserve preferences, and analyze aggregated traffic. We never sell your personal data or index your document files. Learn more in our Privacy Policy.