📘 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.
🎓 Top 15 Udemy Courses (80-90% Discount): My Udemy Courses - Ramesh Fadatare — All my Udemy courses are real-time and project oriented courses.
▶️ Subscribe to My YouTube Channel (176K+ subscribers): Java Guides on YouTube
▶️ For AI, ChatGPT, Web, Tech, and Generative AI, subscribe to another channel: Ramesh Fadatare 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