Hi Guys, Welcome to Proto Coders Point, In this tutorial we will discuss on what is instance variable java with an example.
Instance Variable java definition
An instance variable is declared in a class just outside the method, constructor, or block of code.
Basically, Java Instance Variable gets instantiated/created when an object of a class is created & destroyed when the object is destroyed. So we all know the class definition: An object is an instance of a class & every object has its own copy of the instance variable.
Point to remember about java instance variable
- Instance variable can be accessed only by creating an object.
- No need to set the value to an instance variable, by default “0” is set for number, “false” is set for boolean datatype & “null” is for object references.
- These are non-static variables.
- They are declared inside class just outside method, constructor & block.
- using the “new” keyword, when the object is created the class instance variable will also get created & when the object is destroyed even the instance variable gets destroyed.
- Initialization of class instance variable java can be done by using class object name as shown below.
Person p1 = new Person(); p1.name = "RAJAT PALANKAR"; //initialization value to variable
Instance Variable Java Example
class Person{ //instance variable of class String name; int age; } public class Main { public static void main(String[] args) { //creating person1 Object Person p1 = new Person(); p1.name="RAJAT PALANKAR"; // initializing value p1.age=25; //creating person1 Object Person p2 = new Person(); p2.name="RAM PALANKAR"; p2.age=25; //display data of person 2 System.out.println("Data of person 2"); System.out.println(p2.name); System.out.println(p2.age); } }
In above java code, example on instance variable, we have 2 variable in class person i.e. name & age. I have create multiple object by name p1 & p2, each object has it own copies of variable instance values.
output
Data of person 2 RAM PALANKAR 25
Introduction to java programming