Introduction
A variable acts as a named storage location in memory where data can be stored and retrieved during program execution. Java is a statically typed programming language, which means every variable must be declared with a specific data type before it can be used. This helps the compiler detect errors early and improves code reliability.
Java supports different types of variables based on their scope and lifetime, including local variables, instance variables, and static variables.
What are Java Variables?
A Java variable is a named memory location used to store data that can be accessed and modified during program execution.
Each variable has:
- A data type (such as int, double, or String)
- A name (identifier)
- A value
Example:
int age = 25;
In this example:
- int is the data type.
- age is the variable name.
- 25 is the value assigned to the variable.
Syntax
The general syntax for declaring a variable is:
dataType variableName;
Example:
int marks;
To declare and initialize a variable:
dataType variableName = value;
Example:
int marks = 95;
You can also declare multiple variables of the same type:
int x = 10, y = 20, z = 30;
Types of Variables in Java
Java provides three main types of variables.
1. Local Variable
A local variable is declared inside a method, constructor, or block.
Example:
public class Demo {
public static void main(String[] args) {
int number = 100;
System.out.println(number);
}
}
Characteristics
- Declared inside a method or block.
- Accessible only within that method or block.
- Created when the method starts.
- Destroyed when the method ends.
- Must be initialized before use.
2. Instance Variable
An instance variable is declared inside a class but outside methods, constructors, and blocks.
Example:
public class Student {
String name = "John";
}
Characteristics
- Belongs to an object.
- Each object has its own copy.
- Created when an object is created.
- Destroyed when the object is removed from memory.
- Receives default values if not explicitly initialized.
3. Static Variable
A static variable is declared using the static keyword.
Example:
public class Student {
static String school = "ABC School";
}
Characteristics
- Belongs to the class rather than an object.
- Shared by all objects.
- Created only once when the class is loaded.
- Saves memory when a common value is shared.
Variable Declaration and Initialization
Variables can be declared first and initialized later.
Example:
int age;
age = 30;
Or declared and initialized together:
int age = 30;
Both approaches are valid.
Reassigning Variable Values
Variables can store new values during program execution.
Example:
int marks = 80;
marks = 90;
System.out.println(marks);
Output:
The previous value (80) is replaced by the new value (90).
Example Program
public class VariablesExample {
public static void main(String[] args) {
String name = "Alice";
int age = 22;
double salary = 45000.50;
char grade = 'A';
boolean passed = true;
System.out.println("Name: " + name);
System.out.println("Age: " + age);
System.out.println("Salary: " + salary);
System.out.println("Grade: " + grade);
System.out.println("Passed: " + passed);
}
}
Output
Age: 22
Salary: 45000.5
Grade: A
Passed: true
Default Values of Variables
Local variables do not receive default values and must be initialized before use.
Instance and static variables receive default values automatically.
| Data Type | Default Value |
|---|---|
| byte | 0 |
| short | 0 |
| int | 0 |
| long | 0L |
| float | 0.0f |
| double | 0.0 |
| char | ‘\u0000’ |
| boolean | false |
| Object | null |
Variable Naming Rules
Follow these rules when naming variables.
Valid Names
studentName
totalMarks
employeeSalary
_age
price1
Invalid Names
1student
class
student-name
student name
Rules
- Variable names are case-sensitive.
- Must begin with a letter, _, or $.
- Cannot start with a number.
- Cannot contain spaces.
- Cannot use Java keywords.
- Use meaningful names.
Java Naming Conventions
Although not mandatory, Java follows standard naming conventions.
| Element | Convention | Example |
|---|---|---|
| Variable | camelCase | studentName |
| Constant | UPPER_CASE | MAX_SIZE |
| Class | PascalCase | StudentDetails |
| Method | camelCase | calculateTotal() |
Following conventions improves readability and maintainability.
Real-Life Example
Imagine you’re developing an Employee Management System.
public class Employee {
public static void main(String[] args) {
String employeeName = "Rahul";
int employeeId = 101;
double salary = 65000.00;
boolean active = true;
System.out.println("Employee: " + employeeName);
System.out.println("ID: " + employeeId);
System.out.println("Salary: " + salary);
System.out.println("Active: " + active);
}
}
Variables store employee information that can later be displayed, updated, or processed.
Best Practices
Follow these recommendations when working with variables.
- Use descriptive variable names.
- Follow camelCase naming conventions.
- Initialize local variables before use.
- Keep variable scope as small as possible.
- Use final for values that should not change.
- Avoid unnecessary global variables.
- Choose the appropriate data type to reduce memory usage.
- Group related variables logically.
Common Mistakes
Beginners often make these mistakes.
1. Using an Uninitialized Local Variable
Incorrect:
int number;
System.out.println(number);
This results in a compilation error.
Correct:
int number = 10;
System.out.println(number);
2. Using Invalid Variable Names
Incorrect:
int 1age = 20;
Correct:
int age = 20;
3. Using Java Keywords as Variable Names
Incorrect:
int class = 5;
Correct:
int classNumber = 5;
4. Ignoring Variable Scope
A local variable cannot be accessed outside its method.
Incorrect:
public class Demo {
public void display() {
int number = 100;
}
public void show() {
System.out.println(number);
}
}
Correct: Declare the variable in an appropriate scope or pass it as a parameter.
5. Confusing Static and Instance Variables
Use a static variable only when the value is shared by all objects.
6. Choosing the Wrong Data Type
Incorrect:
int salary = 45000.75;
Correct:
double salary = 45000.75;
Conclusion
Java variables are the building blocks of every Java application. They allow programs to store, retrieve, and manipulate data efficiently. By understanding variable declaration, initialization, scope, lifetime, and the differences between local, instance, and static variables, you can write cleaner and more organized Java code.
Java Variables – Interview Questions
Q 1: What is a variable in Java?
Q 2: How many types of variables are there in Java?
Q 3: What is a local variable?
Q 4: What is an instance variable?
Q 5: What is a static variable?
Java Variables – Objective Questions (MCQs)
Q1. Which of the following is the correct way to declare an integer variable in Java?
Q2. What is the default value of a boolean variable in Java?
Q3. Which of the following variable types are valid in Java?
Q4. What will be the output of the following Java code?
int x = 20;
int y = 10;
System.out.println(x / y);
Q5. In Java, what is the scope of a local variable?