Variables in Java are named memory locations used to store data that can be accessed and manipulated during program execution. Each variable is declared with a specific data type and name and can optionally be initialized with a value.
- Data Type: Specifies the type of data a variable can store, such as int, double, or String.
- Variable Name: Identifies the variable and must follow Java identifier rules.
- Value (Optional): Can be assigned during declaration or later in the program.
class Geeks {
public static void main(String[] args) {
// Declaring and initializing variables
// Integer variable
int age = 25;
// String variable
String name = "GeeksforGeeks";
// Double variable
double salary = 50000.50;
// Displaying the values of variables
System.out.println("Age: " + age);
System.out.println("Name: " + name);
System.out.println("Salary: " + salary);
}
}
Output
Age: 25 Name: GeeksforGeeks Salary: 50000.5
Declaration
The image below demonstrates how we can declare a variable in Java:

From the image, it can be easily perceived that while declaring a variable, we need to take care of two things that are data type of the variable and name.
Initialization
It can be perceived with the help of 3 components explained above:

Example: Here, we are initializing variables of different types like float, int and char.
class Geeks {
public static void main(String[] args) {
// Declaring and initializing variables
// Initializing float variable
float si = 5.5f;
// Initializing integer variables
int t = 10;
int s = 20;
// Initializing character variable
char var = 'h';
// Displaying the values of the variables
System.out.println("Simple Interest: " + si);
System.out.println("Speed: " + s);
System.out.println("Time: " + t);
System.out.println("Character: " + var);
}
}
Output
Simple Interest: 5.5 Speed: 20 Time: 10 Character: h
Naming Rules of Java Variables
- Valid Characters: Variable names can contain Unicode letters and digits, as well as _ and $, according to Java identifier rules.
- Starting Character: A variable name cannot start with a digit. It must begin with a valid identifier-start character, such as a letter, _, or $.
- No Reserved Keywords: Reserved Java keywords such as int, class, and if cannot be used as variable names.
- Case-Sensitive: Java treats names such as age and Age as different variables.
- No Spaces: Variable names cannot contain spaces.
- Meaningful Names: Use descriptive names that clearly indicate the purpose of the variable, such as studentName instead of s.
- Naming Convention: Use camelCase for variable names, such as totalMarks or studentAge.