Rules for Naming Variables in Java

Rules for Naming Variables in Java

 

Java follows strict rules defined by the language specification.

 

A variable name must begin with

 

  • A letter (A–Z or a–z)
  • An underscore _
  • A dollar sign $
  • After the first character, may contain:
    • Letters
    • Digits (09)
    • _ or $

 

Cannot:

 

  • Start with a number

int 1age;   // Invalid

 

  • Contain spaces

int student age;  // Invalid

 

  • Use Java reserved keywords

int class;   // Invalid (class is a keyword)

 

Java is case-sensitive, so:

 

  • int age;
  • int Age;

These are two different variables.

 

Java Naming Conventions (Best Practices)

 

These are not rules (your code will still run), but they are industry standards.

 

Use camelCase for Variables

 

Start with a lowercase letter. Capitalize each new word.

 

  • int studentAge;
  • double accountBalance;
  • String firstName;

 

Use Meaningful Names

 

Good:

  • int totalMarks;
  • double salary;

Bad:

  • int x;
  • double d;

 

Names should describe the purpose of the variable.

 

Boolean Variables

 

Often start with:

  • is
  • has
  • can

 

boolean isActive;

boolean hasLicense;

boolean canVote;

 

Constants (Special Case)

 

Constants use:

  • final keyword
  • ALL CAPITAL LETTERS
  • Words separated by underscore

 

final double PI = 3.14159;

final int MAX_STUDENTS = 50;

 

Summary Table

 

Type

Convention

Example

Normal variable

camelCase

studentName

Boolean variable

camelCase with is/has

isPassed

Constant

UPPER_CASE

MAX_SIZE

 

Why Naming Conventions Matter

  • Improves readability
  • Makes code professional
  • Helps teamwork
  • Follows Java community standards