Following are the kinds of variables categorized according to their scope
  • Static variables
  • Instance variables
  • Method local and Method parameters
  • Block variables
Consider the following program:-



public class Variables {
 static int staticVariable = 1;
 int instanceVariable = 2;

 public void methodName(int methodParameter) {
      int methodLocalVariable = 3;

 if (true) {
      int blockVariable = 4;
 }

 }



Static variables
These variables are declared at the top level. They begins their life when first class loaded into memory and ends when class is unloaded. As they remain in memory till class exist, so these variables often called Class variables. There only one copy of these variables exist
These variables are having highest scope that is they can be accessed from any method/ block in a class
When no explicit assignment made while declaration they are initialized to default values , depending on their type.

Instance variables
These are also declared as the top level variable. They begins their life when object/.instance of class created and ends when object is destroyed. Each copy of this variables belongs an object.
Same as static ones, they initialized to default values depending on their type
They are having less scope as compared, they are accessed only within instance method blocks.

 Method local variables / Method parameters
Method local variables are declared anywhere inside method. their life is started point they declared / initialized and ends when method completes.
These variables are not assigned any default value as case in case of static and instance variables. therefore, they must be initialized when declared or later but before accessing/ using in an expression otherwise compiler will complain.

// other code of class
public void methodName(int methodParameter) {
 int methodLocalVariable ;
 System.out.println(methodLocalVariable);
 }
// other code of class
// If you try to compile above code snippet, compiler will throw following
// VariablesDemo.java:9: variable methodLocalVariable might not have been initialized
// System.out.println(methodLocalVariable);
//                        ^



Method parameters are local variables to method only except their declaration in parameter list of method and they gets value upon invocation.
They are only accessible only in method that they are declared.

Block variables
These are variables that are declared inside any block. They can be accessed only within that block only.
Just like method local variables, they are not assigned any default value. Therefore, It is mandatory to assign value prior to using same in expression/ accessing.

0 comments :

Post a Comment