Instance Variables in Java

Instance variables should declare with in the class but outside of any method or block or constructor.instance variables can accessible inside class all methods , blocks & constructors.

  • Objects store their individual states(values) in Instance Variables.
  • Instance variable values are unique to each Object.
  • Instance variables are stored in Heap Memory.
  • Instance variables can be accessed by using Object reference.
  • Instance Variables will  get default values.
Example for instance variables with default values
File:Instance_Variable_Demo.java
package com.practice;

public class Instance_Variable_Demo {
 int id;// instance variable declaration
 String name;// instance variable declaration
 boolean b;// local variable declaration

 public static void main(String[] args) {
  Instance_Variable_Demo instance_Variable_Demo = new Instance_Variable_Demo();
  System.out.println(instance_Variable_Demo.id);
  System.out.println(instance_Variable_Demo.name);
  System.out.println(instance_Variable_Demo.b);

 }

}
output
0
null
false
Example for instance variables with initialized values
package com.practice;

public class Instance_Variable_Demo {
 int id = 100;// instance variable declaration
 String name = "java2study";// instance variable declaration
 boolean b = true;// local variable declaration

 public void show_Instance_variables() {
  System.out.println(id);
  System.out.println(name);
  System.out.println(b);

 }

 public static void main(String[] args) {
  Instance_Variable_Demo instance_Variable_Demo = new Instance_Variable_Demo();

  instance_Variable_Demo.show_Instance_variables();
 }

}
output
100
java2study
true