A variable is a name given to a memory location. It is the basic unit of storage in a program. The value stored in a variable can be changed during program execution at any point of code.
In Java, all
the variables must be declared before use. We can declare variables in Java
as follows:
datatype variable_name
= value;
Here,
datatype: Type of data that can be stored in this
variable.
variable_name: Name given to the variable.
value: It is the initial value stored in the variable.
The following
figure shows how to declare a Java variable. After variable declaration and initialization
(assigning value to a variable), you can examine the memory view. In this
example, a variable named marks having data type int and value 75 is shown. In
the given figure, you can check memory address 2026 contains the value of the marks
variable.
Fig: Declaring a variable and memory
view after variable definition
Let us have some examples:
float carSpeed;
//Declaring float variable
int time = 10 //Declaring
and Initializing integer variable
char var = 'r';
// Declaring and Initializing character variable
Types of variables
There are three types of variables in Java:
- Local Variables
- Instance Variables
- Static Variables
Fig: Types of
variables in Java
Let us now learn about each one of these variables in
detail.
1. Local Variables
Local variables are variables that are declared and used
within a particular method, constructor, or block of code. They are temporary
and exist only within the scope of the method, constructor, or block in which
they are declared.
Declaration and Scope
To declare a local variable in Java, you specify the
variable's data type, followed by its name. The scope of a local variable is
limited to the block of code in which it is declared. Once the block is exited,
the variable ceases to exist.
Usage and Benefits
Local variables are primarily used for storing temporary
data or intermediate results within a method or block of code. They help in
improving code readability, as they are only accessible within the scope where
they are declared. Local variables also conserve memory since their lifetime is
limited to the duration of the method or block.
Program 2.1: StudentDetails.java
public class EmployeeDetails
{
public void EmployeeAge()
{
//local variable age
int age = 0;
age
= age + 5;
System.out.println("Employee
age is : " + age);
}
public static void main(String
args[])
{
StudentDetails
obj = new StudentDetails();
obj.
EmployeeAge ();
}
}
When you run the program, the output will be:
Employee age
is: 5
In the above program, the variable age is a local variable
to the function EmployeeAge(). If we use the variable age outside EmployeeAge()
function, the compiler will produce an error as shown below.
Program 2.2: EmployeeDetailsInvalid.java
public
class
EmployeeDetailsInvalid
{
public
void
EmployeeAge()
{
//local variable age
int
age = 0;
age
= age + 5;
}
//main function
public
static
void
main(String
args[])
{
//using
local variable age outside it's scope
System.out.println("Employee
age is : " + age);
}
}
When you run the program, the output will be:
error: cannot find symbol
" + age);
The above program will produce an error because variable age is a local variable that is
declared in StudentAge( ), we can’t access it in the main method.
2. Instance Variables:
Instance variables, also known as member variables, are declared within a class but outside any method, constructor, or block. They are associated with objects of the class and have separate copies for each instance of the class.
Declaration and Scope
To declare an instance variable in Java, you specify the
variable's data type, followed by its name, within the class but outside any methods.
Instance variables have class-level scope and are accessible to all methods and
constructors of the class.
Usage and Benefits
Instance variables are used to store and maintain state
information specific to each object of a class. They represent the properties
or attributes of an object and can have different values for each instance.
Instance variables facilitate data encapsulation and provide a way to store and
retrieve object-specific data throughout the lifetime of the objects. To better grasp the concept of
instance variables, let's examine a program that illustrates their usage.
Program 2.3: InstanceVariable.java
import
java.io.*;
class Marks
{
//These
variables are instance variables.
//These
variables are in a class and are not inside any function
int
engMarks;
int
mathsMarks;
int
phyMarks;
}
class MarksDemo
{
public
static void main(String args[])
{
//first object
Marks
obj1 = new Marks();
obj1.engMarks
= 50;
obj1.mathsMarks
= 80;
obj1.phyMarks
= 90;
//second
object
Marks
obj2 = new Marks();
obj2.engMarks
= 80;
obj2.mathsMarks
= 60;
obj2.phyMarks
= 85;
//displaying
marks for the first object
System.out.println("Marks
for the first object:");
System.out.println(obj1.engMarks);
System.out.println(obj1.mathsMarks);
System.out.println(obj1.phyMarks);
//displaying
marks for the second object
System.out.println("Marks
for the second object:");
System.out.println(obj2.engMarks);
System.out.println(obj2.mathsMarks);
System.out.println(obj2.phyMarks);
}
}
When you run the program, the output will be:
Marks for the
first object:
50
80
90
Marks for the
second object:
80
60
85
In the provided program, we have two classes:
"Marks" and "MarksDemo." The "Marks" class
contains instance variables that are declared at the class level, outside any
method. These variables represent the marks obtained in English, Mathematics,
and Physics.
In the "MarksDemo" class, we create two objects:
obj1 and obj2, using the "Marks" class. We assign values to the
instance variables of these objects to represent the marks obtained in
different subjects.
Finally, we display the marks for both objects, printing the
values of the instance variables using System.out.println() statements.
3. Static Variables:
Static variables, also known as class variables, are
declared within a class and are prefixed with the static keyword. Unlike
instance variables, static variables have only one copy, shared by all
instances of the class.
Declaration and Scope
To declare a static variable in Java, you specify the
variable's data type, followed by the static keyword and its name, within the
class but outside any methods. Static variables have class-level scope and can
be accessed directly using the class name.
Usage and Benefits
Static variables are useful for storing data that is shared
across multiple instances of a class. They are commonly used for constants,
counters, or values that need to be accessed globally within the class or even
outside the class. Static variables provide memory efficiency by having only
one instance regardless of the number of objects created.
class Example{
int data=50;
//instance variable
static int m=100;
//static variable
void method(){
int n=90;
//local variable
}
}
Let's understand the concept of static variables in more
detail with the help of a program.
Program 2.4: StaticVariable.java
import
java.io.*;
class
Emp {
//
static variable salary
public
static
double
salary;
public
static
String name =
"Ali";
}
public
class
EmpDemo
{
public
static
void
main(String args[]) {
//accessing
static variable without
object
Emp.salary
= 1000;
System.out.println(Emp.name
+ "'s average salary:"+ Emp.salary);
}
}
When you run the program, the output will be:
Ali's
average salary:1000.0
Use Cases
Local variables are commonly used for storing
temporary or intermediate values within a method or block of code.
Instance variables are used to represent the state or
properties of objects and hold data specific to each instance of a class.
Static variables are useful for storing data shared
across multiple instances of a class or maintaining global data.
Comparison among Local variables, Static variables, and Instance variables in Java
Local Variables |
Instance Variables |
Static Variables |
|
Scope |
Limited to
the block of code where they are declared |
Accessible
throughout the class where they are declared |
Accessible
throughout the class where they are declared |
Lifetime |
Created when
the block of code is executed and destroyed when it completes execution |
Exist as long
as the instance of the class exists |
Exist as long
as the program runs or the class is loaded |
Initialization |
Must be
explicitly initialized before use |
Can have
default values or be explicitly initialized |
Can have
default values or be explicitly initialized |
Access |
Accessed only
within the block of code where they are declared |
Accessed
using the "this" keyword or instance reference |
Accessed
using the class name or instance reference |
Number of Copies |
Each
execution of the block of code creates a new instance |
Each instance
of the class has its own copy |
Only one copy
exists for the entire class |
Memory Allocation |
Stack |
Heap |
Data segment
of the program |
Usage Examples |
Temporary
variables inside functions/methods |
Object-specific
data (e.g., properties) |
Shared data
among multiple instances of a class |
Short Questions about Variables in Java
Q1. Can a local variable have the same name as an
instance variable or a static variable?
Yes, a local variable can have the same name as an instance
variable or a static variable within a different scope. In such cases, the
local variable takes precedence within its scope.
Q2. Are local variables thread-safe in Java?
Local variables are thread-safe by nature since they are
only accessible within the method or block in which they are declared. Each
thread executing the method or block will have its own copy of the local
variables.
Q3. Can we declare static variables inside a method in
Java?
No, static variables cannot be declared inside a method in
Java. They are always declared at the class level and outside any methods.
Q4. Can instance variables be accessed without creating
objects?
No, instance variables can only be accessed through object
references. You need to create an instance of the class to access its instance
variables.
Q5. Is it possible to change the value of a final
instance variable in Java?
No, a final instance variable cannot be modified once it has
been assigned a value. It remains constant throughout the lifetime of the
object.
Understanding the differences between local variables, instance variables, and static variables is essential for writing efficient and well-structured Java code. Local variables provide temporary storage, instance variables maintain object-specific states, and static variables store data shared among instances. By utilizing the appropriate variable type in your code, you can ensure better memory management, encapsulation, and code readability. This part is the continuation of our previous article.