Variables?
A Java variable is a piece of memory that can contain a data value.A variable thus has a data type.Variables are typically used to store information which our Java program needs to do its task.
Syntax:data-type variable_name= value;
for eg: int a=10;
Variables Types:-
On basic of position and declaration variables are classified as:
- Local variable
- Instance variable
- Static variable
Local variable:
- A variable defined inside method or block is called a local variable.
- A scope of these variable exists only within block in which the variable is declared i.e one can access the variable within that block or method only.
- Initialization of variable is mendatory otherwise code is not executed.
Example:
class Test{
public static void main (String args[]){
//local variables
int a=10;
System.out.println("value of a is"+a);
}
}
Output:

Instance variable:
- Variables which are declared in a class but not inside a particular method are called instance variables.
- These variables are created when object of class is created.Initialization is not mendatory.
- If these variables are not initialized then they return default values 0 or false.
- Value of variable is varied from object to object.
- These can't be accessed from static area directly,firstly we have to create object.
Example:
class Test{
//instance variable
int i=100;
public static void main(string args[]){
Abc a1=new Abc();
System.out.println(a1.i);
}
Output:

Static variable
-
Static variable also known as class variable.
- These variable declared as same as instance variable but with static keyword within class.
- Value is not varied from object to object.
- They can access directly using class name.
Example:
class Static{
//static variable
static String sum="Sum:";
static String diff="Difference:";
public static void main(String[]args)
{
int a=10;
int b=20;
int c=a+b;
int d=a-b;
System.out.println(sum+c);
System.out.println(diff+d);
}
}
Output: