Sunday, August 10, 2014

static keyword in Java

static keyword is being used in the JAVA world extensively, reason for this use us as follows:


1. static keyword has to do with the memory management.
2. The static variable gets memory only once in class area at the time of class loading.

a very classic example of point2 is as below:

if you write test cases in JUnit, you may come across @BeforeClass, @AfterClass, @Before, @After annotations. As you must be aware that @BeforeClass and @AfterClass are executed only once, @BeforeClass at the time of class loading, @AfterClass after all the test cases are executed, therefore it is safe to use static keyword with any method that has to be executed for @BeforeClass or @AfterClass.
You may also be aware that @Before methods and @After methods are executed for each @Test method i.e. in JUnit test cases are executed between @Before and @After, if you try to use the static keyword with any method associated with @Before or @After it will result into a compiler error. Try this code in eclipse where JUnit is setup properly and to see the compiler error put static keyword for methods defined inside @Test annotation or @Before annotation or @After annotation:



import org.junit.BeforeClass;
import org.junit.Before;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Test;
import org.junit.Ignore;

public class JunitExecution {

       @BeforeClass
       public static void BeforeClass()
       {
             System.out.println("Entering BeforeClass");
       }
      
       @AfterClass
       public static void AfterClass()
       {
             System.out.println("Entering AfterClass");
       }
      
       @Before
       public void Before()
       {
             System.out.println("Entering Before");
       }
      
       @After
       public void After()
       {
             System.out.println("Entering After");
       }
      
      
       @Test
       public void test1()
       {
             System.out.println("Inside Test1");
       }
      
       @Test
       public void test2()
       {
             System.out.println("Inside Test2");
       }
      
       @Ignore
       public void ignore()
       {
             System.out.println("Inside ignore");
       }
}


if you remember, we always use static keyword while defining main in Java, reason is that main need to be executed only once:
public static void main(String args[])

A very nice tutorials to completely understand about "static" and refer again and again is - http://www.javatpoint.com/static-keyword-in-java

No comments:

Post a Comment