Declaring & Initializing Variables
Variables are named containers that hold data in your Java programs. Every variable in Java has a specific data type that determines what kind of data it can store and how much memory it uses.
35 min•By Priygop Team•Last updated: Feb 2026
What is a Variable?
A variable is like a labeled box where you store a value. In Java, you must declare the data type of every variable before using it. This is called 'static typing' — it helps the compiler catch errors early and makes your code more reliable. You can declare, initialize, and reassign variables as needed.
Variable Declaration & Initialization
Example
public class VariableDemo {
public static void main(String[] args) {
// Declaration: telling Java the type and name
int age;
// Initialization: giving the variable a value
age = 25;
// Declaration + Initialization together (recommended)
String name = "Alice";
double salary = 55000.75;
boolean isActive = true;
char grade = 'A';
// Multiple variables of the same type
int x = 10, y = 20, z = 30;
// Printing variables
System.out.println("Name: " + name);
System.out.println("Age: " + age);
System.out.println("Salary: $" + salary);
System.out.println("Active: " + isActive);
System.out.println("Grade: " + grade);
System.out.println("Sum: " + (x + y + z));
}
}Try It Yourself: Create Variables
Try It Yourself: Create VariablesJava
Java Editor
✓ ValidTab = 2 spaces
Java|19 lines|640 chars|✓ Valid syntax
UTF-8