📘 Premium Read: Access my best content on Medium member-only articles — deep dives into Java, Spring Boot, Microservices, backend architecture, interview preparation, career advice, and industry-standard best practices.
✅ Some premium posts are free to read — no account needed. Follow me on Medium to stay updated and support my writing.
🎓 Top 10 Udemy Courses (Huge Discount): Explore My Udemy Courses — Learn through real-time, project-based development.
▶️ Subscribe to My YouTube Channel (172K+ subscribers): Java Guides on YouTube
Instance variable in Java is used by Objects to store their states. Variables which are defined without the STATIC keyword and are Outside any method declaration are Object specific and are known as instance variables. They are called so because their values are instance specific and are not shared among instances.
Java Instance Variable Example
package net.javaguides.corejava.variables;
public class InstanceVariableExample {
public static void main(String[] args) {
Employee employee = new Employee();
// Before assigning values to employee object
System.out.println(employee.empName);
System.out.println(employee.id);
System.out.println(employee.age);
employee.empName = "Ramesh";
employee.id = 100;
employee.age = 28;
// After assigning values to employee object
System.out.println(employee.empName);
System.out.println(employee.id);
System.out.println(employee.age);
}
}
class Employee {
// instance variable employee id
public int id;
// instance variable employee name
public String empName;
// instance variable employee age
public int age;
}
null
0
0
Ramesh
100
28
Rules for Instance variable in Java
- Instance variables can use any of the four Access Modifiers - Public, Private, Protected & Default
- They can be marked final
- They can be marked transient
- They cannot be marked abstract
- They cannot be marked synchronized
- They cannot be marked strictfp
- They cannot be marked native
- They cannot be marked static
Comments
Post a Comment
Leave Comment