Variable Declaration Syntax
What you'll learn: How to properly declare variables in Java using type-first syntax and valid naming rules.
The Basic Pattern
When you create a variable in Java, you must follow a specific syntax pattern:
type variableName;
The type comes first (like int, double, char, or boolean), followed by a name you choose. This tells Java two things: what kind of data the variable will hold, and what you'll call it in your code.
Declaration Examples
Here's how you declare variables of different types:
int age;
double price;
char grade;
boolean isActive;
long population;
Each line creates a "container" that can hold a value of that specific type. Think of it like labeling empty boxes before you put things in them—Java needs to know what kind of box you're creating.
Naming Rules You Must Follow
Your variable names must:
- Start with a letter, underscore
_, or dollar sign$ - Contain only letters, digits, underscores, or dollar signs
- Not be a Java keyword (like
int,true,class)
int count; // valid
int _temp; // valid
int $value; // valid
int user2; // valid
int 2fast; // INVALID - starts with digit
int my-variable; // INVALID - contains hyphen
By convention, variable names use camelCase: start with lowercase, capitalize each new word (like studentScore or maxHeight).
Key Takeaway: Java variables require type-first declaration syntax (type name;), and names must follow strict rules while conventionally using camelCase for readability.