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
Related Examples
Reference
Continue Learning with Java Guides
Want to take your programming skills to the next level? Explore my practical Udemy courses on Java, Spring Boot, Microservices, Full-Stack Development, Docker, and Generative AI. You can also follow my structured learning roadmaps to become a professional developer.
By Ramesh Fadatare - Udemy Instructor Partner
Comments
Post a Comment
Leave Comment