Variables
A variable is a named piece of memory that holds a value your program can read and change. Before you can use one, you must declare it with a type and a name.
Declaring a Variable
The basic form is type name = value;. The type tells Java what kind of data the variable can hold.
int age = 25;
double price = 19.99;
String name = "Sonu";
boolean isActive = true;
You can also declare a variable first and assign a value later, as long as you give it a value before you try to use it:
int score;
score = 100;
Variable Naming Rules
Java is strict about what counts as a valid variable name (an identifier):
| Rule | Example |
|---|---|
Can contain letters, digits, underscore _, and dollar sign $ | total_1, $price |
| Cannot start with a digit | 1total is invalid |
| Case-sensitive | total and Total are different variables |
| Cannot be a reserved keyword | int, class, public can't be used as names |
totalAmount) — this isn't enforced by the compiler, but it's expected in readable Java code.Declaring Multiple Variables at Once
If several variables share the same type, you can declare them together on one line, separated by commas:
int x = 1, y = 2, z = 3;
Final Variables (Constants)
Adding the final keyword makes a variable's value unchangeable once assigned. Use it for values that
should never change, like configuration values or mathematical constants.
final double PI = 3.14159;
// PI = 3.0; // this would cause a compile error
final constants are named in ALL_CAPS_WITH_UNDERSCORES, e.g. MAX_USERS.Variable Scope (A Quick Look)
Where a variable is declared determines where it can be used — this is called its scope. A local variable is declared inside a method and only exists while that method runs. An instance variable is declared inside a class but outside any method, and belongs to each object created from that class. We'll cover this in much more depth once we reach object-oriented programming.