There are three different types of variables a class can have in Java are local variables, instance variables, and class/static variables.
Local Variable
A local variable in Java can be declared locally in methods, code blocks, and constructors. When the program control enters the methods, code blocks, and constructors then the local variables are created and when the program control leaves the methods, code blocks, and constructors then the local variables are destroyed. A local variable must be initialized with some value.
Example
public class LocalVariableTest { public void show() { int num = 100; // local variable System.out.println("The number is : " + num); } public static void main(String args[]) { LocalVariableTest test = new LocalVariableTest(); test.show(); } }
Output
The number is : 100
Instance Variable
An instance variable in Java can be declared outside a block, method or constructor but inside a class. These variables are created when the class object is created and destroyed when the class object is destroyed.
Example
public class InstanceVariableTest { int num; // instance variable InstanceVariableTest(int n) { num = n; } public void show() { System.out.println("The number is: " + num); } public static void main(String args[]) { InstanceVariableTest test = new InstanceVariableTest(75); test.show(); } }
Output
The number is : 75
Static/Class Variable
A static/class variable can be defined using the static keyword. These variables are declared inside a class but outside a method and code block. A class/static variable can be created at the start of the program and destroyed at the end of the program.
Example
public class StaticVaribleTest { int num; static int count; // static variable StaticVaribleTest(int n) { num = n; count ++; } public void show() { System.out.println("The number is: " + num); } public static void main(String args[]) { StaticVaribleTest test1 = new StaticVaribleTest(75); test1.show(); StaticVaribleTest test2 = new StaticVaribleTest(90); test2.show(); System.out.println("The total objects of a class created are: " + count); } }
Output
The number is: 75 The number is: 90 The total objects of a class created are: 2