A variable stores a value that your program can use. For example, you can use variables to store a person’s name, age, or membership status.
In this example, you will declare variables, update a value, and print the results.
Source code
public class VariablesExample {
public static void main(String[] args) {
String name = "Alice";
int age = 25;
double heightInMeters = 1.68;
boolean member = true;
// Update an existing variable.
age = age + 1;
// Let the compiler infer the type from the initial value.
var greeting = "Hello, " + name + "!";
// A final variable cannot be reassigned.
final int monthsInYear = 12;
System.out.println(greeting);
System.out.println("Age: " + age);
System.out.println("Height: " + heightInMeters + " m");
System.out.println("Member: " + member);
System.out.println("Months in a year: " + monthsInYear);
}
}
Explanation
To declare a variable with an explicit type, write the type, a name, and an optional initial value:
int age = 25;
Here, int is the type, age is the variable name, and 25 is its initial value. The = operator assigns the value to the variable.
The example uses these types:
| Type | Variable | Purpose |
|---|---|---|
String |
name |
Stores text |
int |
age |
Stores a whole number |
double |
heightInMeters |
Stores a floating-point number |
boolean |
member |
Stores true or false |
You can assign a new value to an existing variable without repeating its type:
age = age + 1;
This statement reads the current value of age, adds one, and stores the result back in age. Its value changes from 25 to 26.
For a local variable, you can also use var:
var greeting = "Hello, " + name + "!";
The compiler infers that greeting has the type String. Its type stays fixed after the declaration. A variable declared with var must have an initial value from which the compiler can determine its type. See the Java SE 25 specification on local variable declarations.
Use final when a variable should not be reassigned:
final int monthsInYear = 12;
Assigning another value to monthsInYear later would cause a compilation error.
Finally, System.out.println() prints each result on a separate line. The + operator joins text with the variable values.
Run the example
With JDK 25 or later installed, compile and run the file:
javac VariablesExample.java
java VariablesExample
Output
Hello, Alice!
Age: 26
Height: 1.68 m
Member: true
Months in a year: 12
All variables in this example are local variables because they are declared inside the main() method. Initialize local variables before reading their values, and choose names that make their purpose clear.
