For working professionals
For fresh graduates
More
6. JDK in Java
7. C++ Vs Java
16. Java If-else
18. Loops in Java
20. For Loop in Java
45. Packages in Java
52. Java Collection
55. Generics In Java
56. Java Interfaces
59. Streams in Java
62. Thread in Java
66. Deadlock in Java
73. Applet in Java
74. Java Swing
75. Java Frameworks
77. JUnit Testing
80. Jar file in Java
81. Java Clean Code
85. Java 8 features
86. String in Java
92. HashMap in Java
97. Enum in Java
100. Hashcode in Java
104. Linked List in Java
108. Array Length in Java
110. Split in java
111. Map In Java
114. HashSet in Java
117. DateFormat in Java
120. Java List Size
121. Java APIs
127. Identifiers in Java
129. Set in Java
131. Try Catch in Java
132. Bubble Sort in Java
134. Queue in Java
141. Jagged Array in Java
143. Java String Format
144. Replace in Java
145. charAt() in Java
146. CompareTo in Java
150. parseInt in Java
152. Abstraction in Java
153. String Input in Java
155. instanceof in Java
156. Math Floor in Java
157. Selection Sort Java
158. int to char in Java
163. Deque in Java
171. Trim in Java
172. RxJava
173. Recursion in Java
174. HashSet Java
176. Square Root in Java
189. Javafx
In Java, three main types of variables are classified based on their scope and usage: local variables, static variables, and instance variables. Each type serves a different purpose, and understanding their differences is crucial for effective programming.
For example, when building a student registration system, each student may have unique attributes such as name, age, and roll number. These properties need to be stored individually for each student object, which is where instance variables come into play.
In this blog, we’ll focus on Instance Variables in Java- what they are, how they work, and how they differ from static variables. We’ll also cover their default values and features, and how to implement instance variables in a Java program.
Let’s dive into the details and clear up any confusion about instance variables in Java!
An instance variable in Java is declared inside a class but outside of any method, constructor, or block. It belongs to an object, not the class. So, every time you create a new object, a new copy of the instance variable is created.
These variables store data that is specific to each object. For example, if you create two Student objects, each will have its own name, age, and roll number.
Ready to build robust Java applications? Enroll in our Software Engineering course and enhance your coding skills with real-world software development practices.
When not initialized explicitly, instance variables in Java are assigned default values based on their data types:
Data Type | Default Value |
byte | 0 |
short | 0 |
int | 0 |
long | 0L |
float | 0.0f |
double | 0.0d |
char | '\u0000' |
boolean | false |
Object | null |
Combine Java programming with cutting-edge AI. Join the Executive Diploma in Data Science & AI with IIIT-B and unlock career opportunities in tech.
Implementing Instance Variable in a Java Program
To understand how instance variables work in real scenarios, let’s implement them in a simple Java program. This will show how these variables store unique values for each object and how they are accessed within instance methods.
Example:
Think of an online shopping cart system. Each product in the cart has a specific productName, price, and quantity. Since every product object should store its own unique details, these fields are declared as instance variables.
class Product {
// Instance variables
String productName;
double price;
int quantity;
// Constructor to initialize instance variables
Product(String productName, double price, int quantity) {
this.productName = productName;
this.price = price;
this.quantity = quantity;
}
// Method to display product details
void displayProductInfo() {
System.out.println("Product: " + productName);
System.out.println("Price: $" + price);
System.out.println("Quantity: " + quantity);
System.out.println("------------------------");
}
public static void main(String[] args) {
Product p1 = new Product("Laptop", 49999.99, 1);
Product p2 = new Product("Mouse", 599.50, 2);
p1.displayProductInfo();
p2.displayProductInfo();
}
}
Output
Product: Laptop
Price: $49999.99
Quantity: 1
------------------------
Product: Mouse
Price: $599.5
Quantity: 2
------------------------
Explanation:Here, productName, price, and quantity are instance variables. Each product object has its own set of values. Even when multiple products are created, the data remains separate for each, demonstrating how instance variables store object-specific information.
From Java development to AI solutions—earn a DBA in Emerging Technologies with Generative AI and gain the skills needed for tomorrow’s tech landscape.
An instance initializer block is a block of code enclosed within {} (just like a method body), but not inside any method or constructor. It runs every time an object is created, right after the instance variables are initialized and before the constructor runs.
It's commonly used when you want to write common initialization code for all constructors without repeating it in each constructor.
Example:
Let’s say we want every Employee object to have a default company name and display a message whenever an object is created.
class Employee {
String name;
int id;
String company;
// Instance initializer block
{
company = "TechCorp";
System.out.println("Instance initializer block executed.");
}
// Constructor
Employee(String name, int id) {
this.name = name;
this.id = id;
}
void displayInfo() {
System.out.println(name + " | " + id + " | " + company);
}
public static void main(String[] args) {
Employee e1 = new Employee("Alice", 101);
e1.displayInfo();
}
}
Output:
Instance initializer block executed.
Alice | 101 | TechCorp
Instance methods are used when you want a method to act on the data stored in instance variables-which are unique to each object.
Here’s why they’re important:
Instance methods are designed to work with instance variables—those defined at the class level but outside any method. These variables are unique to each object. Instance methods can read, modify, or use these variables directly, making it easy to build logic that works with object-specific data without passing parameters.
Each object created from a class can have its own data. Instance methods allow actions that are dependent on this data. For example, if you create two employee objects with different salaries, an instance method can calculate taxes or bonuses differently for each, ensuring personalized, object-specific behavior based on internal state.
Rather than writing the same logic repeatedly for each object, you can define it once in an instance method. Each object can call this method with its own data, making the code more organized and efficient. It reduces redundancy and improves maintainability while following the DRY (Don’t Repeat Yourself) principle.
Instance methods support encapsulation by combining data (instance variables) and behavior (methods) within the same class. They can be declared private or public, controlling access to internal data. This safeguards the object’s state from unwanted changes and helps enforce rules on how that data is accessed or modified.
Example:
Let’s say you’re building a basic system for managing book records in a library. Each book has a title and an author. You want to display each book’s details when needed. Since each book is a separate object, you need a method that can access and display the unique details of each book. That’s where instance methods help.
class Book {
String title;
String author;
// Instance method to display book details
void displayDetails() {
System.out.println("Title: " + title);
System.out.println("Author: " + author);
}
public static void main(String[] args) {
Book book1 = new Book();
book1.title = "Atomic Habits";
book1.author = "James Clear";
Book book2 = new Book();
book2.title = "The Alchemist";
book2.author = "Paulo Coelho";
book1.displayDetails(); // Calls instance method on book1
book2.displayDetails(); // Calls instance method on book2
}
}
Output
Title: Atomic Habits
Author: James Clear
Title: The Alchemist
Author: Paulo Coelho
Explanation:
The displayDetails() instance method accesses the instance variables title and author specific to each book object. This allows the method to behave differently based on the object calling it, helping maintain object-specific behavior and clean code reuse.
Aspect | Instance Variable | Static Variable |
Definition | A variable defined inside a class but outside any method, and belongs to an object. | A variable defined with the static keyword inside a class and shared across all objects. |
Memory Allocation | Memory is allocated each time a new object is created. | Memory is allocated once at class loading time, regardless of how many objects exist. |
Belongs To | Each object of the class has its own copy. | Class itself, not the individual objects. |
Accessed By | Accessed using object reference (e.g., obj.name). | Accessed using class name or object (e.g., ClassName.counter). |
Keyword | No special keyword required. | Requires the static keyword during declaration. |
Use Case | Used when each object needs to store different data. | Used when data is common across all objects, like a counter or config. |
Default Values | Gets default values if not initialized (e.g., int → 0, String → null). | Also gets default values similarly. |
Example Use | Storing a student’s name or roll number (unique per student). | Counting total number of students registered (shared count). |
Polymorphism Support | Instance variables support polymorphism when accessed through methods. | Static variables do not support polymorphism. |
Encapsulation Impact | Helps in encapsulating object-specific data. | Good for shared data but should be used carefully to avoid tight coupling. |
Modification Scope | Modifying in one object does not affect others. | Modifying the value affects all instances, as it's stored at the class level. |
Instance variables in Java are essential for storing object-specific data, allowing each object to maintain its state. Understanding their behavior and differences from static variables enhances your grasp of object-oriented programming. By leveraging instance variables, you can create more efficient and organized code in your Java applications.
Instance variables are variables declared within a class but outside of any method, constructor, or block. They store object-specific data, with each object having its own copy. These variables define the attributes of an object and can be accessed by instance methods.
Instance variables belong to an object and exist as long as the object exists. Local variables, however, are defined within methods or blocks and only exist during the method's execution. Instance variables can be accessed throughout the object, while local variables are limited to their scope.
Yes, instance variables can be initialized in the constructor. This allows you to provide specific values for each object when it is created, ensuring each object starts with its own set of unique values.
The default value of an instance variable depends on its data type. For example, numeric types are initialized to 0, boolean variables to false, and reference types to null. These defaults apply if you don't explicitly initialize the variables.
No, instance variables and static variables are two different things. Instance variables belong to individual objects, while static variables belong to the class and are shared across all instances. Instance variables cannot be static.
The scope of an instance variable is the entire class. Instance methods and constructors within the class can access it. However, it is specific to each object, and its value can vary from one object to another.
Static methods belong to the class rather than any specific instance, so they cannot directly access instance variables. To access instance variables in a static method, you need to create an object of the class and access the variable through that object.
If an instance variable is not explicitly initialized, it will take the default value corresponding to its data type. For example, an uninitialized int will default to 0, and a String will default to null.
In Java, interfaces can’t have instance variables, but they can have constants (static final variables). Instance variables are specific to classes and require object instantiation, whereas interfaces provide a contract for behavior.
Instance variables can be accessed directly within instance methods of the same class. They can also be accessed from other classes through object references, using the dot notation (object.variable), provided they are not private.
The this keyword refers to the current instance of the class. It is commonly used to differentiate between instance variables and local variables when they have the same name. By using this, you explicitly reference the instance variable.
Take the Free Quiz on Java
Answer quick questions and assess your Java knowledge
Author
Talk to our experts. We are available 7 days a week, 9 AM to 12 AM (midnight)
Indian Nationals
1800 210 2020
Foreign Nationals
+918068792934
1.The above statistics depend on various factors and individual results may vary. Past performance is no guarantee of future results.
2.The student assumes full responsibility for all expenses associated with visas, travel, & related costs. upGrad does not provide any a.