Java Variables:

  • Variable is a name of memory location where the value is stored to use within class, Method etc…
  • Each variable in Java has a specific Datatype to store Value.
  • Which decides the size and layout of the java variables memory.
  • Values can be put away inside that memory, and the arrangement of activities that can be connected to the variable.

 

There are three different kinds of variable in Java

  1. Local variables
  2. Instance variables
  3. Class / Static variables

Variable Declaration:

 

1) Local variables 

  • Local java variables can be declared within methods, constructors, or blocks.
  • Local variables are created when the method, constructor or block is entered and the variable will be destroyed once it exits the method, constructor or block.
  • Access modifiers cannot be used for local variables Because Local Variables defined within method.
  • Local variable can be declared within the method, constructor or block.

 

Example:

In following example, age is a local variable which is defined inside Age() method and having its scope limited to the Age() method only.

Output:

 

2) Instance variables 

  • Instance java variables are declared in a class, but outside a method, constructor etc.
  • When a space is allocated for an object in the heap, a memory slot for each instance variable value is created.
  • Instance variables are created when an object is created and destroyed when the object is destroyed.
  • Instance variables hold values that must be referenced by more than one method, constructor or block.
  • Access modifiers can be given for instance variables.

 

Example: 

In following example, name is a local variable which is defined inside Employee class.

Output:

 

3) Class / static variables 

  • class java variables is also referred to as static variable and declared with the static key-word in a category, but it is outside a method, constructor or a block.
  • only one replica of every class variable is created, regardless of how many objects are created.
  • Static variables are stored in static memory.
  • Static variables are created while the program begins and destroyed while this system stops.

 

Example:

Output: