Do you think IIT Guwahati certified course can help you in your career?
No
Introduction
Variables in Java can be declared in different sections of the code, and based on this, their memory location can change. For example, instance variables are stored in the heap memory segment and are unique to each class object. On the other hand, class variables are shared by all class objects.
So, let’s dive deep into the instance variable in Java.
What is a Variable in Java?
A variable in Java is a named storage location used to store data that can change during the execution of a Java program. Variables provide you a way to work with and manipulate data in a program. In Java, there are three types of variables:-
Instance Variables
Class Variables
Local Variables
In the next section, we will discuss instance variables in Java.
What is Instance Variable in Java?
An instance variable is defined inside a class but outside of any constructor, method, or block. They are stored in the heap section of the memory. It is used to represent that each object of the class should have its own copy of the instance variable. For example, each time you create a new class object, it will have its copy of the instance variables.
Syntax of Java Instance Variables
Instance Variables are defined using the syntax.
class ClassName {
datatype variableName;
}
where,
Class is the access modifier.
The datatype is the data type of the instance variable, such as int, double, or float.
variableName is the instance variable specified.
We will look into more examples as we go further.
Features of Instance Variable in Java
An instance variable is specified inside a class but outside of any constructor, method, or block.
They are unique to each instance of the class.
They can be accessed and modified by any method or constructor in the class.
They can be accessed and modified using the dot notation, such as objectName.instanceVariableName.
They can have different access modifiers, such as private, public, or protected.
They are destroyed when the object is destroyed.
Initialization of Java Instance Variables
In Java, instance variables are variables that belong to an instance of a class. These variables are initialized when an object of the class is created. The initialization is typically done within a constructor, a special method that is called when an instance of the class is instantiated.
A constructor in Java has the same name as the class and does not have a return type. It is used to initialize the instance variables of the class. Here is an example of how instance variables can be initialized in Java:
public class MyClass {
// Instance variables
private int variable1;
private String variable2;
// Constructor
public MyClass(int value1, String value2) {
this.variable1 = value1;
this.variable2 = value2;
}
}
In this example, variable1 and variable2 are instance variables. The constructor MyClass is used to initialize these variables when a new object of the class is created. The this keyword is used to distinguish between instance variables and parameters with the same name. This initialization process ensures that each object of the class has its own set of data, thus maintaining the integrity of the object's state.
How to Access Instance Variables?
We usually access instance variables in 2 ways
Using “this” keyword
Using object references
Let's understand both methods in detail.
1. Using this Keyword
The this keyword in Java refers to the current instance of the class. It helps differentiate between instance variables and parameters with the same name, especially in constructors or methods.
class Employee {
String name;
int age;
// Constructor using 'this' keyword
Employee(String name, int age) {
this.name = name; // refers to the instance variable 'name'
this.age = age; // refers to the instance variable 'age'
}
void display() {
System.out.println("Name: " + this.name + ", Age: " + this.age);
}
}
public class Main {
public static void main(String[] args) {
Employee emp = new Employee("John", 30);
emp.display(); // Output: Name: John, Age: 30
}
}
In this example, this.name and this.age refer to the instance variables of the Employee class. The this keyword is used in the constructor to differentiate between the instance variables and constructor parameters.
2. Using Object References
An object reference is a pointer to an instance of a class, and it can be used to access the instance variables. You can assign values to instance variables using the reference variable of the object.
class Car {
String model;
int year;
// Constructor
Car(String model, int year) {
this.model = model;
this.year = year;
}
void display() {
System.out.println("Model: " + model + ", Year: " + year);
}
}
public class Main {
public static void main(String[] args) {
Car car1 = new Car("Tesla", 2024); // Using object reference
car1.display(); // Output: Model: Tesla, Year: 2024
Car car2 = new Car("BMW", 2023); // Another object reference
car2.display(); // Output: Model: BMW, Year: 2023
}
}
Here, car1 and car2 are object references that point to instances of the Car class. They are used to access and modify the instance variables model and year.
Advantages of Instance Variable in Java
Let's look at some of the advantages of Instance Variable in Java:
They can be accessed by any method of the class, which can be very useful for accessing data between methods.
They are used to create relationships between objects.
Management of data structures can be done using instance variables in Java.
Disadvantages of Instance Variable in Java
Let's look at some of the disadvantages of Instance Variables in Java:
They take up a lot of memory.
It cannot be declared static, abstract, synchronised, or native.
They can be prone to errors if they are not properly mentioned or can also be difficult to understand if not written in a proper way.
Default Values of Instance Variables in Java
Let’s look at some of the default values of instance variables in Java:
Data Types
Default Value
int
0
boolean
false
double
0.0d
object
null
char
\u0000
long
0L
float
0.0
byte
0
short
0
Now let’s look at a code to understand the instance variable in Java.
How To Implement Instance Variable In Java?
The code written below defines a class called “occupation”. The class has two instance variables, “name” and “job”. The class has a method called “printInfo” which prints the name and occupation of a person.
Finally, there is a main method that creates an occupation object called job1 and the printInfo method is then called, which prints the name and occupation of the person.
Java
Java
public class Occupation { // Instance variables String name; String job;
Instance variables in Java are used whenever we need to represent the state of an object and its properties. They are declared inside a class but outside of any method. The value of an instance variable can vary from object to object. It is also used whenever we need to share data between methods in a class.
Instance variables allow you to create more flexible and reusable classes in Java. They are also suitable for scenarios where different objects of the same class must store and manage individual data independently.
Difference Between Local, Static and Instance Variables in Java
Feature
Local Variables
Static Variables
Instance Variables
Definition
Variables declared inside a method, constructor, or block.
Variables declared with the static keyword, shared among all instances of a class.
Variables declared in a class but outside any method, specific to each instance.
Scope
Limited to the method, constructor, or block where they are declared.
Throughout the class, accessible via the class name or instance.
Limited to the instance of the class where they are declared.
Lifetime
Exists only during the execution of the method, constructor, or block.
Exists for the lifetime of the class, from when it is first loaded into memory until it is unloaded.
Exists as long as the instance of the class exists.
Default Value
No default value; must be explicitly initialized.
Default value is 0 for numeric types, false for boolean, and null for object references if not explicitly initialized.
Default value is 0 for numeric types, false for boolean, and null for object references if not explicitly initialized.
Memory Allocation
Allocated on the stack.
Allocated in the static memory of the heap.
Allocated in the heap as part of the object.
Access Modifier
Cannot have access modifiers (e.g., private, public).
Can have access modifiers.
Can have access modifiers.
Usage
Typically used for temporary storage or calculations within methods.
Used for class-wide fields, constants, and utility methods.
Used for attributes that need to be unique to each object instance.
Example Declaration
int localVar = 10;
static int staticVar = 10;
int instanceVar = 10;
Access
Directly within the method.
ClassName.staticVar or objectName.staticVar
objectName.instanceVar
Frequently Asked Questions
What is the difference between instance variable and class variable?
Instance variables hold unique data for each object, while class variables share a single value across all objects.
Where are instance variables stored in Java?
Instance variables in Java are stored in the heap memory, which is allocated to each individual object created from a class. Each object has its own copy of instance variables.
Can instance variables be declared as static?
No, instance variables cannot be declared as static. Static variables belong to the class, not to specific instances. However, instance variables are specific to each object, while static variables are shared across all instances of the class.
When are instance variables created and destroyed?
Instance variables are created when an object is instantiated (in the constructor). They are destroyed when the object is eligible for garbage collection, i.e., when there are no more references to the object.
Conclusion
This article discussed the basic syntax of instance variable in Java and the difference between local, static and instance variable in Java.
In conclusion, instance variables in Java are important for representing the state and attributes of objects within a class. They are defined within the class but outside methods or constructors and stored on the heap segment of memory. Each object created from the class has its own copy of instance variables.