14. Usage of Static Variables

Static Variables

   1. Static variables are also known as Class Variables.
   2. Such variables get default values based on the data type.
   3. Data stored in static variables is common for all the objects( or instances ) of that Class.
   4. Memory allocation for such variables only happens once when the class is loaded in the memory.
   5. These variables can be accessed in any other class using class name.
   6. Unlike non-static variables, such variables can be accessed directly in static and non-static methods.

Example 1: Static variables can be accessed without reference in Static method

class Example7{
  static int var1;
  static String var2;
  //Its a Static Method
  public static void main(String args[])
  {
      System.out.println("Var1 is:"+Var1);
      System.out.println("Var2 is:"+Var2);
  }
}

Output:
Var1 is:0

Var2 is:null

No comments:

Post a Comment