Variables and identifiers
Variables and identifiers
Section titled “Variables and identifiers”Variables
Section titled “Variables”A variable is a named memory location that holds a value. In Java, every variable has a type that determines what kind of data it can store.
Variable declaration syntax:
type identifier [ = value ];Example:
int age;double salary = 45000.50;char grade = 'A';boolean isActive = true;Identifiers
Section titled “Identifiers”Identifiers are names given to variables, methods, classes, packages, etc. Java has strict rules for identifiers:
- Can contain letters, digits, underscores (
_), and dollar signs ($). - Must not start with a digit.
- Are case‑sensitive (
ageandAgeare different). - Cannot be a reserved keyword (like
int,class,public).
Valid identifiers:
int score;double _price;String $name;int counter1;Invalid identifiers:
int 1stPlace; // starts with a digitdouble class; // 'class' is a keywordString my-name; // hyphen not allowedNaming conventions (recommended):
- Variables and methods:
camelCase(e.g.,studentName,calculateTotal()) - Classes:
PascalCase(e.g.,Student,BankAccount) - Constants:
UPPER_SNAKE_CASE(e.g.,MAX_VALUE,PI)