Variables in Java Explained for Beginners
Introduction: What Are Variables in Java?
When writing a Java program, we often need to store data such as numbers, names, or results.
This stored data can change while the program is running.
To store such data, Java uses variables.
What Is a Variable?
A variable is a named memory location used to store data that can change during program execution.
In simple words:
A variable is like a container that holds information.
Why Variables Are Important in Java
Variables allow a program to:
Store user input
Perform calculations
Remember values
Produce meaningful output
Without variables, programs would be static and useless.
How to Declare a Variable in Java
In Java, a variable must be declared before it is used.
Syntax
dataType variableName;Example
int age;
Here:
int→ data typeage→ variable name
How to Assign a Value to a Variable
You can assign a value using the assignment operator (=).
age = 25; Or combine declaration and assignment:
int age = 25;Using Variables in a Java Program
Example
class Demo {
public static void main(String[] args) {
int number = 10;
System.out.println(number);
}
}
Output:
10Rules for Naming Variables in Java
Java follows specific rules for variable names:
- Must start with a letter,
_, or$ - Can contain letters and digits
- Cannot start with a number
- Cannot use Java keywords
- Case-sensitive
Valid Variable Names
agetotalMarks_count
Invalid Variable Names
1numberclasstotal marks
Types of Variables in Java
Java variables are mainly divided into three types.
1. Local Variables
Definition
Variables declared inside a method.
Characteristics
Created when method is called
Destroyed when method ends
Must be initialized before use
Example
void display() {
int x = 10;
}
2. Instance Variables
Definition
Variables declared inside a class but outside methods.
Characteristics
Belong to an object
Each object gets its own copy
Example
class Student {
int age;
}
3. Static Variables
Definition
Variables declared using the static keyword.
Characteristics
Shared among all objects
Only one copy exists
Example
class College {
static String name = "ABC College";
}
Real-Life Analogy
Think of variables like labeled boxes:
The label → variable name
The box → memory location
The item inside → value
You can replace the item, but the box remains.
Frequently Asked Questions (FAQs)
Q1. Can a variable change its value in Java?
Yes. Variables can store different values during program execution.
Q2. Can I declare multiple variables at once?
Yes.
int a = 5, b = 10; Q3. Is Java case-sensitive with variables?
Yes. Age and age are different variables.
Q4. Can variables store text?
Yes, using the String data type.
Q5. What happens if a variable is not initialized?
Local variables cause an error; instance variables get default values.