Instance Variable Example Java Program


Definition

Variables are identifiers associated with values. They are declared by writing the variable's type and name, and are optionally initialized in the same statement by assigning a value. Instance variables are declared inside a class but outside a method. They can been seen by all methods in the class.

Instance Variable Example Program

public class InstanceVariableDemo{
	public String str1;
		private String str2;
		public InstanceVariableDemo (String empName){
		str1 = empName;
	}
	public void salary(String empSal){
		str2 = empSal;
	}
    public void disp(){
    System.out.println( str1 );
    System.out.println( str2 );
	}
	public static void main(String args[]){
		InstanceVariableDemo obj = new InstanceVariableDemo("This is an instance variable and is visible to all child classes");
		obj.salary("The variable str2 is visible only inside methodOne");
		obj.disp();
	}
}

Sample Output

Output is:
This is an instance variable and is visible to all child classes
The variable str2 is visible only inside methodOne