What is a Variable?

  • A variable is a named memory location used to store a value.

  • That value can be changed during the program execution.

Syntax:

dataType variableName = value; 

Ex:

int age=10; String animal="Tiger"; 

Here , age and animal are variables that contains some value.

Types of Variables:

There are mainly three types of variables:

 - Local variable - Instance variable - Static variable 

Local Variable:

  • Variable which is declared inside a method , constructor or block is called Local Variable.
  • You must initialize the value for local variable, before accessing it.
  • These local variables can be accessed within that block only.
  • Local Variables don't have Default values.

ex:

class Animal { public void Dog() { int age=5; //Local Variable String name="Puppy"; //Local Variable System.out.println("Name of the Dog:"+name+"\nAge of the dog:"+age); } public static void main (String[] args) { Animal a=new Animal(); a.Dog(); } } 

Output:

Name of the Dog:Puppy Age of the dog:5 

Here, name and age are the local variables. We can't access the local variables outside the block. If we try to access the local variables outside the block the compiler throws a compilation error.

Instance Variable:

  • Variable which is declared inside a class outside methods, constructor or block is called Instance Variable.
  • Instance variables belongs to object.
  • Each object has it own copy.
  • Instance variables have default value if they are not explicitly initialized.
  • We can access the instance variables using objects.

Ex:

class Animal { String name="Tiger"; //Instance Variable int age=13; //Instance Variable  public static void main (String[] args) { Animal a=new Animal(); System.out.println("Animal Name:"+a.name); System.out.println("Animal Age:"+a.age); } } 

Output:

Animal Name:Tiger Animal Age:13 

Static Variable:

  • A variable declared inside a class using the static keyword is called a static variable.
  • Static variables belongs to class.
  • Only one copy of a static variable is created and shared among all objects of that class.
  • Static variables have default value if they are not explicitly initialized.

  • We can access the static variable using its class name.

Ex:

class Birds { static String name="Parrot"; //static variable static String home="Trees"; // static variable public static void printing() { System.out.println("Bird name:"+name+"\nBird's Home:"+home); } public static void main (String[] args) { System.out.println(Birds.name); System.out.println(Birds.home); Birds.printing(); } } 

Output:

Parrot Trees Bird name:Parrot Bird's Home:Trees