Pages

Tuesday, February 5, 2013

Knowing static Keyword in Java

static keyword in Java is used basically in 3 different scenarios of which include Static Methods, Static Variables and Static Blocks of Code. 




Static Variables


  • Variables which belong only to the class but NOT the object (instance of the class) are called static variables. 
  • Static variables are initialized only once at the starting of the execution of the program and these are the variables which are initialized first before any of the instance variables available. 
  • To access a static variable we don't require any object to be initialized but we can access it directly using the class name itself as ClassName.Variable
  • If no value is assigned to the static variables then they are assigned to their standard default values.Non-static variables CANNOT be referenced using the above syntax i.e., ClassName.Variable

Example of Static Variables and Accessing Them : http://pastie.org/6049699

Static Methods

  • Similar to the static variables, static methods belong to the class in which they are defined but not the instance of the class i.e., the object.
  • Static Methods CANNOT access non-static variables i.e., instance variables but they can only access static variables of the same class. 
  • Non-static methods CANNOT be called from a static methods but static methods only can be called.
  • Object initialization is NOT required to access a static method of a class but it can be accessed directly by the class name as ClassName.Method();
  • A static method CANNOT refer to this or super keyword in any way. 
Main Method is always static as it should be accessible to run before any instantiation takes place. 
Example of Static Methods and Access Them : http://pastie.org/6049764

Static Blocks Of Code

This is a simple concept, it is a block of code which is executed when a class is first loaded into the JVM. Static Blocks always pertain to a particular class but NOT outside the classes. Static Blocks are simply written using the keyword static

Static blocks are generally used to initialize the static data members like we have constructors to initialize instance variables of a class. 

Syntax :

class BlocksEx {
    static {
    //code here
    }
}


0 comments:

Post a Comment