A variable is a named memory location used to store a value that a Java program can work with. During program execution, that value can remain unchanged or be replaced with another value, depending on how the variable is declared and used.
A useful way to think about a variable is as a labeled container. The label is the variable name, the type describes what kind of value the container can hold, and the current value is the data stored inside it.
int age = 25; String name = "Rahul"; double salary = 45000.50;
In this example, age, name, and salary are variables. Their declared types determine what kind of values they can store.
Why Variables Exist
Programs rarely work with one fixed value from beginning to end. A student's marks may change, a shopping cart total may increase, and a user's login status may change during execution. Variables give programs a way to remember and manipulate these values.
int score = 75;
score = 90;
System.out.println(score);
The variable score first stores 75 and later stores 90. The latest assigned value is printed.
Remember: A variable has a name, a type, and a current value. The value can change during execution unless the variable is subject to a restriction such as final.
Variable Declaration
Declaring a variable means telling Java its type and its name.
int age; String name; double price;
These declarations create variables without explicitly assigning initial values.
For local variables, Java requires a value to be assigned before the variable is read.
int age;
System.out.println(age);
This produces a compilation error because the local variable age has not been initialized.
Variable Initialization
Initialization means assigning the first value to a variable.
int age = 25;
Here, int is the data type, age is the variable name, and 25 is the initial value.
Declaration and initialization can also be written separately:
int age;
age = 25;
Both approaches are valid. Initializing a variable at the point of declaration is often clearer when the initial value is already known.
Declaration, Initialization, and Assignment
| Term | Meaning | Example |
|---|---|---|
| Declaration | Defines the variable's type and name. | int age; |
| Initialization | Gives a variable its first value. | int age = 25; |
| Assignment | Stores a value in an already declared variable. | age = 30; |
Changing a Variable's Value
A normal variable can receive a new value as long as the new value is compatible with its declared type.
int quantity = 2;
quantity = 5;
quantity = 10;
The variable does not create a new name each time. The same variable is updated with a new value.
Java Variable Types
Variables in Java are commonly discussed according to where they are declared: local variables, instance variables, and static variables.
| Type | Declared Where | Associated With |
|---|---|---|
| Local variable | Inside a method, constructor, or block | That particular execution scope |
| Instance variable | Inside a class but outside methods | An object |
| Static variable | Inside a class with static | The class itself |
Local Variables
A local variable is declared inside a method, constructor, or block. It can be accessed only within its applicable scope.
public static void main(String[] args) { int age = 25; System.out.println(age); }
The variable age exists within the scope of the main() method. Code outside that scope cannot directly access it.
Instance Variables
An instance variable is declared inside a class but outside methods, constructors, and blocks. Each object of the class normally gets its own copy of an instance variable.
class Student { String name; int age; }
If two Student objects are created, each object can have a different name and age.
Student student1 = new Student(); Student student2 = new Student(); student1.name = "Amit"; student2.name = "Priya";
The two objects maintain separate instance values.
Static Variables
A static variable belongs to the class rather than to each individual object. It is declared using the static keyword.
class Employee { static String companyName = "Tech Solutions"; }
The variable companyName is shared by the class rather than independently stored for every employee object.
Primitive Variables
A primitive variable stores a value of one of Java's primitive data types.
byte age = 25; int marks = 95; long population = 8000000L; float temperature = 36.5F; double salary = 55000.75; char grade = 'A'; boolean passed = true;
Primitive variables are used when the program needs direct values such as numbers, characters, or boolean states.
Reference Variables
A reference variable stores a reference to an object rather than directly representing the object's complete data.
String name = "Rahul"; Student student = new Student();
Here, name is a reference variable referring to a String object, while student refers to a Student object.
Variable Scope
Scope defines where a variable can be accessed in a program. Understanding scope becomes extremely important as programs grow.
if (true) { int number = 100; System.out.println(number); } System.out.println(number); // Invalid
The variable number exists only inside the block where it was declared. After the closing brace, that local variable is outside its scope.
Beginner tip: When you see a variable-related compilation error, check both its type and its scope. A correctly declared variable can still be inaccessible from the location where you are trying to use it.
Variable Naming
Java variable names should follow standard naming conventions. The usual style is camelCase.
int studentAge; double productPrice; String customerName; boolean paymentCompleted;
Names should communicate meaning. Compare x with totalPrice. Both may compile, but the second immediately tells the reader what the value represents.
Multiple Variables in One Declaration
Java allows multiple variables of the same type to be declared in a single statement.
int x = 10, y = 20, z = 30;
Although this is valid syntax, separate declarations can sometimes be easier to read, especially when variables have different meanings.
int studentCount = 10; int teacherCount = 20; int classroomCount = 30;
Type Compatibility
A variable can store values that are compatible with its declared type.
int age = 25; double price = 99.99; double value = age;
Java can automatically widen an int value to a double. The reverse conversion requires explicit casting because information could be lost.
double price = 99.99; int value = (int) price;
The result of the cast is 99 because the fractional portion is discarded during this conversion.
Final Variables
A variable declared with final cannot be assigned a new value after it has been initialized.
final double PI = 3.14159;
Trying to reassign it causes a compilation error.
final int MAX_USERS = 100; MAX_USERS = 200; // Invalid
The final keyword is commonly used when a value should not be reassigned. Naming conventions for constants are discussed in the next related topic, constants.
Variable Lifetime
A variable's lifetime depends on where it is declared. A local variable is associated with the execution of its scope, while an instance variable exists as part of an object, and a static variable is associated with the class.
This distinction becomes especially important when working with objects, memory management, methods, and multithreaded applications.
Common Beginner Mistakes
- Using a local variable before initializing it.
- Assigning an incompatible value to a variable.
- Trying to change a final variable.
- Using a variable outside its scope.
- Using unclear names such as x, a, or temp for important data.
- Confusing declaration with initialization.
- Assuming every variable is automatically initialized, regardless of where it is declared.
Best Practices
- Use meaningful and descriptive variable names.
- Initialize local variables before using them.
- Keep variables as close as practical to the code that uses them.
- Use the narrowest appropriate scope.
- Use final when a reference or value should not be reassigned.
- Avoid declaring many unrelated variables in a single statement.
- Choose the appropriate data type instead of using a larger type without a reason.
Interview Insights
| Question | Key Point |
|---|---|
| What is a variable? | A named storage location used by a program to hold a value. |
| What is variable declaration? | Specifying the variable's type and name. |
| What is initialization? | Assigning the first value to a variable. |
| What is a local variable? | A variable declared inside a method, constructor, or block. |
| What is an instance variable? | A non-static field associated with an object. |
| What is a static variable? | A variable associated with the class rather than individual objects. |
| Can a final variable be reassigned? | No, once it has been initialized, it cannot be assigned another value. |
Quick Revision
| Concept | Example | Meaning |
|---|---|---|
| Declaration | int age; | Defines type and name |
| Initialization | int age = 25; | Provides the first value |
| Assignment | age = 30; | Updates an existing variable |
| Local variable | int count = 10; | Declared inside a method or block |
| Instance variable | String name; | Belongs to an object |
| Static variable | static int count; | Belongs to the class |
| Final variable | final int MAX = 100; | Cannot be reassigned after initialization |
Variables are one of the first concepts that turn a Java program from a collection of fixed instructions into something that can actually remember and process changing information. Once you understand declaration, initialization, assignment, scope, and the difference between local, instance, and static variables, many later Java concepts become much easier. The key habit is simple: choose the right type, give the variable a meaningful name, and keep its scope as focused as possible.
