Static keyword in java - variable, method, class, block - 25 salient features - Differences between static and instance/non-static variable, methods, block and nested class


Contents of page :
  • Static in java >
  • Static can be used with following in java >
    • 1) variable
    • 2) method
    • 3) static class
    • 4 block
  • Where does static variable, method, class are stored in memory?

  • 1) Static variable
    • Diagram to where static variables are stored in memory & static variables remain same for different objects of class>
    • Program to show value of static variables will remain same for different objects of class but for every new object instance variables will be initialized to new value>
    • Bad practice regarding accessing static variable>
    • Difference between static and non-static variable>

  • 2) Static method
    • Program for accessing static method>
    • About main method >
    • Bad practice regarding accessing static method>
    • Difference between static and non-static method>
    • Static method cannot be overridden >
    • Program to static method cannot be overridden>

  • 3) Static class
    • Program for accessing static nested class>
    • Difference between static and non-static class>

  • 4) Static block / Static initialization block
    • Difference between static and non-static block>
    • Program to show static blocks are called as soon as class is loaded even before instance of class is created (i.e. before constructor is called) >

  • Summary - 20 salient features of static keyword >



Static in java >
The static is a keyword in java.

Static can be used with following in java >
  • 1) variable
  • 2) method
  • 3) static class
  • 4 block


Where does static variable, method, class are stored in memory?
Static variable, method, class are stored in perm gen(permanent generation memory).


1) Static variable
  • static variables are also known as class variables.

  • We need not to create instance of class for accessing static variables.

  • static variables will remain same for different instance/objects of class but for every new object instance variables will be initialized to new value.




Diagram to where static variables are stored in memory & static variables remain same for different objects of class>

It's important to know that only the static variables and their values (primitives or references) are stored in PermGen space.
If static variable is a reference to an object that which is stored in the normal sections of the heap (string pool, young/old generation or survivor space). Those objects are not stored in PermGen space.
Example code >
static int id = 1; //the value 1 is stored in the permgen area.

static Employee emp = new Employee (); //the reference(i.e. emp ) is
                   //stored in the permgen area, the object is not.

static String company="XYZ pvt ltd"; //the reference(i.e. company) is
                   //stored in the permgen area, but  "XYZ pvt ltd" is not,
                   //"XYZ pvt ltd" gets stored in String pool.




Program to show value of static variables will remain same for different objects of class but for every new object instance variables will be initialized to new value>
class Employee{
   int id;
   String name;
   static String company="XYZ pvt ltd";
  
   public Employee(int id, String name) {
          this.id = id;
          this.name = name;
   }
   @Override
   public String toString() {
          return "Employee [id=" + id + ", name=" + name + ", company=" + company + "]";
   }
  
  
}
/** Copyright (c), AnkitMittal JavaMadeSoEasy.com */
public class StaticVariableTest {
   public static void main(String[] args) {
          Employee emp1=new Employee(1, "ankit");
          Employee emp2=new Employee(2, "sam");
          System.out.println(emp1);
          System.out.println(emp2);
   }
}
/*OUTPUT
Employee [id=1, name=ankit, company=XYZ pvt ltd]
Employee [id=2, name=sam, company=XYZ pvt ltd]
*/
In the above program static variable was initialized at time of declaration, and its value will remain same for all instances of class, that’s why they are also called as class variables.


Bad practice regarding accessing static variable>
Using instance.staticVariable is bad practice.
Example - emp1.company
You will face compiler warning=”The static field Employee.company should be accessed in a static way”
Resolution>
We must use ClassName.staticVariableName   
Example - Employee.company


Difference between static and non-static variable>
Static variables
Non-static variables
Known only as class variables.
Also known as instance variables.
Static variables can be accessed inside >
static block, non-static block (instance block),
static method, non-static method (instance method),
Non-static variables can be accessed inside >
non-static block (instance block),
non-static method (instance method),
methods of inner class.
in methods of static nested class.
Static variables are class variables access to them is always resolved during compile time.
Non-Static variables are instance variables access to them is always resolved during runtime.
instance variables are serialized in java




2) Static method
  • static methods are also known as class methods.
  • We need not to create instance of class for accessing static methods.
  • Static methods can access all static variables, but cannot access non-static (instance variables)

Important points about overriding static methods >
  • Static method cannot be overridden, any attempt to do this will not cause compilation error.

  • Static method cannot be overridden with non-static method, any attempt to do this will cause compilation error.

  • Non-static method cannot be overridden with static method, any attempt to do this will cause compilation error.

Program for accessing static method>
/** Copyright (c), AnkitMittal JavaMadeSoEasy.com */
public class StaticMethodTest{
   public static void main(String[] args) {
          staticMethod();
   }
   static void staticMethod() {
          System.out.println("in staticMethod()");
   }
         
}
/*OUTPUT
in staticMethod()
*/

About main method >
main method itself is static method, which is invoked by JVM, JVM does not create instance of class for accessing main method.


Bad practice regarding accessing static method>
Using instance.staticMethod() is bad practice.
You will face compiler warning=”The static method should be accessed in a static way”
Resolution>
We must use ClassName.staticMethod()   

Difference between static and non-static method>
Static method
Non-static method
Known only as class method.
Also known as instance method.
Only static variables can be accessed inside static method
Static and non-static variables (instance variables) can be accessed inside static method.
We need not to create instance of class for accessing static methods.
We need to create instance of class for accessing non-static methods.
Static methods cannot be overridden.

Because static methods are class methods, access to them is always resolved during compile time only using the compile time type information.
Non-static methods can be overridden.

Because non static methods are instance methods, access to them is always resolved during runtime time only using the runtime object.



Static method cannot be overridden >
Its one of the favourite question of interviewers. Intention is to test few basic core java concepts.
Static method cannot be overridden, any attempt to do this will not cause compilation error, but the results won’t be same when we would have overridden non-static methods.
But why?
Overriding in Java means that the method would be called on the run time based on type of the object and not on the compile time type of it .

But static methods are class methods access to them is always resolved during compile time only using the compile time type information.

Accessing static method using object references is a bad practice (discussed above) and just an extra liberty given by the java designers.

EXAMPLE>
In below program access to SuperClass’s static method() is resolved during compile time  only using the compile time type information (i.e. by using SuperClass obj), means calling obj.method() is always going to invoke static method() of SuperClass.
Assign any sub type object to reference of superclass [obj=new SubClass()] won’t have any impact on call to static method at runtime.

Accessing static method using object references is bad practice (discussed above) and just an extra liberty given by the java designers.

Program to static method cannot be overridden>
class SuperClass{
   static void method(){
          System.out.println("superClass method");
   }
}
class SubClass extends SuperClass{
   static void method(){
          System.out.println("SubClass method");
   }
}
/** Copyright (c), AnkitMittal JavaMadeSoEasy.com */
public class StaticMethodTest {
  
   public static void main(String[] args) {
          SuperClass obj=new SubClass();
          obj.method();
   }
         
}
/*OUTPUT
superClass method
*/

If non-static methods would have been used in above program, output would have been
subClass method


3) Static class
  • static class are also known as
  • Top level class can never be static in java.
  • Only static variables can be accessed inside static nested class.
  • StaticNestedClass can be abstract or final.
  • StaticNestedClass can be private, protected, public.
  • strictfp modifier can also be used with StaticNestedClass.
  • Static nested classes can declare static initialization blocks
  • Static nested classes can declare member interfaces.



Note : Static nested class is not a inner class, its just a nested class.



Program for accessing static nested class>
class Employee{
  
   //Inner class
   class InnerClass {
          public void method() {
                 System.out.println("In InnerClass's method");
          }
   }
  
   //static nested class
   static class StaticNestedClass{
      public void method(){
          System.out.println("In StaticNestedClass's method");
       }
   }
}
/** Copyright (c), AnkitMittal JavaMadeSoEasy.com */
public class StaticClassTest {
   public static void main(String[] args) {
         
          //Accessing inner class
          new Employee().new InnerClass().method();
         
          //Accessing static nested class
          new Employee  .    StaticNestedClass().method();
   }
         
}
/*OUTPUT
In InnerClass's method
In StaticNestedClass's method
*/


Difference between static and non-static class>
Static class
class (Non-static class)
Top level class can never be static in java.
Top level class is always non static in java.
static class are also known as static nested classes.
Top level class is just called as class .
But,
nested class is known as >
  • inner class or
  • member inner class.
Only Static member variables of outer class can be accessed inside methods of static nested class.
Static and non-static member variables of outer class can be accessed inside methods of non-static class
Accessing method of static nested class

new OuterClass .    StaticNestedClass().method();

-Instance of top level class is not needed, we need to have instance of static nested class only
Accessing method of inner class

new OuterClass().new InnerClass().method();

Instance of top level class and InnerClass is needed.
         



4) Static block / Static initialization block
  • static blocks are called as soon as class is loaded even before instance of class is created (i.e. before constructor is called)
  • static block are also known as static initialization blocks in java.
  • Any code written inside static block is thread safe.

Difference between static and non-static block>
Static block
Non-static blocks
Known as static initialization blocks.
Also known as instance initialization  blocks.
static blocks executes before instance blocks.
instance blocks executes after static blocks.
Only static variables can be accessed inside static block
Static and non-static variables (instance variables) can be accessed inside instance block.
static blocks can be used for initializing static variables
or
calling any static method.
instance blocks can be used for initializing instance variables
or
calling any instance method.
static blocks executes when class is loaded.
instance block executes only when instance of class is created, not called when class is loaded.
this keyword cannot be used in static blocks.
this keyword can be used in instance block.


Program to show static blocks are called as soon as class is loaded even before instance of class is created (i.e. before constructor is called) >
class Employee {
   /*
   * Static block
   */
   static {
          System.out.println("static block");
   }
   /*
   * Non-Static block (Instance block)
   */
   {
          System.out.println("non-static block");
   }
   /*
   * Constructor
   */
   Employee() {
          System.out.println("Employee constructor");
   }
}
/** Copyright (c), AnkitMittal JavaMadeSoEasy.com */
public class StaticBlockTest {
   public static void main(String[] args) {
         
          //Create instance of Employee.
          new Employee();
         
   }
         
}
/*OUTPUT
static block
non-static block
Employee constructor
*/





Summary  - 25 salient features of static keyword >

  1. The static is a keyword in java.
  2. Static variable, method, class are stored in perm gen(permanent generation memory).
Static variable
  1. static variables are also known as class variables.
  2. We need not to create instance of class for accessing static variables.
  3. static variables will remain same for different instance/objects of class but for every new object instance variables will be initialized to new value.
  4. Static variables can be used inside constructor.
  5. Its important to know that only the variables and their values (primitives or references) are stored in PermGen space.
If static variable is a reference to an object that which is stored in the normal sections of the heap (string pool, young/old generation or survivor space). Those objects are not stored in PermGen space.
  1. Using instance.staticVariable is bad practice, We must use ClassName.staticVariableName   

Static method
  1. static methods are also known as class methods.
  2. We need not to create instance of class for accessing static methods.
  3. Static methods can access all static variables, but cannot access non-static (instance variables)

Important points about overriding static methods >
  1. Static method cannot be overridden, any attempt to do this will not cause compilation error.

  1. Static method cannot be overridden with non-static method, any attempt to do this will cause compilation error.

  1. Non-static method cannot be overridden with static method, any attempt to do this will cause compilation error.

Static class
  1. static class are also known as

  1. Top level class can never be static in java.
  2. Only static variables can be accessed inside static class.

Static block
  1. static blocks are also known as static initialization blocks in java.
  2. static blocks executes as soon as class is loaded even before instance of class is created (i.e. before constructor is called).
  3. static blocks executes before instance blocks.
  4. Any code written inside static block is thread safe.
  5. Only static variables can be accessed inside static block
  6. static blocks can be used for initializing static variables or  calling any static method.
  7. this keyword cannot be used in static blocks.



RELATED LINKS>

Inner class/ nested class, static nested class, local and anonymous inner class in java


final keyword in java - 20 salient features


String pool/ String literal pool/ String constant pool in java

eEdit
Must read for you :